Pagini recente » Cod sursa (job #673514) | Cod sursa (job #416086) | Cod sursa (job #2201428) | Cod sursa (job #1967546) | Cod sursa (job #587514)
Cod sursa(job #587514)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int N = 50050;
const int INF = 1000000000;
struct pereche
{
int nod,cost;
};
vector<pereche> a[N];
priority_queue<pair<int,int> > h;
int n,d[N];
bool s[N];
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
void citire()
{
int m,i,x,y,c;
in>>n>>m;
for(i=1 ; i<=m ; i++)
{
in>>x>>y>>c;
a[x].push_back((pereche){y,c});
}
}
void init()
{
for(int i=0 ; i<=n ; i++)
d[i] = INF;
}
int vf_cost_min()
{
while(!h.empty())
{
if(!s[h.top().second])
return h.top().second;
h.pop();
}
return 0;
}
void actualizare(int x)
{
int c,y;
for(size_t i=0 ; i<a[x].size() ; i++)
{
y = a[x][i].nod;
c = a[x][i].cost;
if(d[x] + c < d[y])
{
d[y] = d[x] + c;
h.push(make_pair(-d[y],y));
}
}
}
void dijkstra(int x0)
{
int x;
d[x0] = 0;
h.push(make_pair(d[x0],x0));
for(int i=1 ; i<n ; i++)
{
x = vf_cost_min();
if(d[x] == INF)
return;
s[x] = true;
actualizare(x);
}
}
void afisare()
{
for(int i=2 ; i<=n ; i++)
if(d[i] == INF)
out<<"0 ";
else
out<<d[i]<<" ";
}
int main()
{
citire();
init();
dijkstra(1);
afisare();
return 0;
}