Pagini recente » Cod sursa (job #2165013) | Cod sursa (job #106110) | Cod sursa (job #383124) | Cod sursa (job #2749822) | Cod sursa (job #1600357)
#include <iostream>
#include <fstream>
#define NMax 50001
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
const int inf = 1 << 28;
int H[NMax],D[NMax],M[NMax],P[NMax],n,m,k;
struct Muchie{int nod, cost; Muchie* nod_urmator;};
Muchie * V[NMax];
void add(int a,int b,int c){
Muchie *p;
p=new Muchie;
p->nod=b;
p->cost=c;
p->nod_urmator=V[a];
V[a]=p;
}
void upheap(int nod){
int t=nod>>1;
while(t){
if(D[H[t]]<D[H[nod]]){
P[H[t]]=nod;
P[H[nod]]=t;
swap(H[t],H[nod]);
nod=t;
t=nod>>1;
}else{
t=0;
}
}
}
void downheap(int nod){
int f=nod<<1;
while(f<=k){
if(f+1<=k){
if(D[H[f]]>D[H[f+1]]){
f++;
}
}
if(D[H[f]]<D[H[nod]]){
P[H[f]]=nod;
P[H[nod]]=f;
swap(H[f],H[nod]);
nod=f;
f=nod<<1;
}else{
return;
}
}
}
void dijkstra(int p){
for(int i=1;i<=n;i++){
D[i]=inf;
P[i]=-1;
}
D[p]=0;
P[p]=1;
H[++k]=p;
while(k){
int min=H[1];
swap(H[1],H[k]);
P[H[1]]=1;
k--;
downheap(1);
Muchie *q;
q=new Muchie;
q=V[min];
while(q){
if(D[q->nod]>D[min]+q->cost){
D[q->nod]=D[min]+q->cost;
if(P[q->nod]!=-1){
upheap(P[q->nod]);
}else{
H[++k]=q->nod;
P[H[k]]=k;
upheap(k);
}
}
q=q->nod_urmator;
}
}
}
void read(){
int p;
f>>n>>m;
for(int i=0,a,b,c;i<m;i++){
f>>a>>b>>c;
add(a,b,c);
add(b,a,c);
}
dijkstra(1);
bool ok=true;
for(int i=2;i<=n;i++){
//if(D[i]!=M[i])
//ok=false;
g<<D[i]<<" ";
}
/* if(ok)
g<<"DA";
else
g<<"NU";
g<<endl;*/
}
int main()
{
int t=0;
read();
return 0;
}