Pagini recente » Cod sursa (job #604187) | Cod sursa (job #1010877) | Cod sursa (job #986758) | Cod sursa (job #300495) | Cod sursa (job #763475)
Cod sursa(job #763475)
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 50001
#define INF 0xfffffff
vector<pair<int,int> >g[MAX];
struct nod{ int x,c; }h[MAX];
int n,d[MAX],pos[MAX],k; // numarul de noduri din heap
void remove(){
pos[h[1].x] = 0; // nodul dat nu se mai gaseste in heap
h[1] = h[k--]; // aducem ultimul nod in virf
// sil actualizam in heap
int t = 1, f = 2;
if(k <= 3 && h[3].c < h[2].c)f = 3;
while(f<=k && h[t].c > h[f].c)
{
swap(h[t],h[f]); // interschimbam nodurile
swap(pos[h[t].x],pos[h[f].x]); // interschimbam pozitiile in heap
t = f; f = 2*t;
if(f+1<=k && h[f+1].c < h[f].c)f++;
}
}
void update(int c,int x){
int t,f;
if(pos[x] == 0)
{
k++; // introducem un nod nou
h[k].x = x;
h[k].c = c;
f = k; // trebuie actualizat nodul respectiv
} else
{
f = pos[x]; // trebuie actualizat nodul la pozitia lui curenta
h[f].c = c;
}
t = f/2;
while(t > 0 && h[t].c > h[f].c)
{
swap(h[t],h[f]);
swap(pos[h[t].x],pos[h[f].x]);
f = t; t = f/2;
}
}
void dijkstra(){
for(int i=2;i<=n;i++)d[i]=INF;
h[1].x = 1; h[1].c = 0; k = 1; // initializam heapul
pos[1]=1; // nodul 1 se afla in virful heapului
while(k > 0)
{
int x,y,c,cm;
c=h[1].c;
x=h[1].x;
remove(); // stergem nodul dat din heap
for(int i=0;i<g[x].size();i++)
{
cm=g[x][i].first;
y=g[x][i].second;
if(d[y] > c + cm)
{
d[y] = c + cm;
update(d[y],y); // actualizam nodul dat in heap
}
}
}
}
int main(){
int m,x,y,c;
freopen("dijkstra.in","r",stdin);
freopen("dijkstra.out","w",stdout);
scanf("%d %d",&n,&m);
while(m--)
{
scanf("%d %d %d",&x,&y,&c);
g[x].push_back(make_pair(c,y));
}
dijkstra();
for(int i=2;i<=n;i++) printf("%d ",d[i]==INF ? 0 : d[i]);
return 0;
}