Pagini recente » Cod sursa (job #3144136) | Cod sursa (job #849160) | Cod sursa (job #349195) | Cod sursa (job #3252077) | Cod sursa (job #440820)
Cod sursa(job #440820)
#include <cstdio>
#include <vector>
using namespace std;
#define MAX 50005
#define INF 0x3f3f3f3f
typedef vector<pair<int,int> >::iterator iter;
int n,m,heap[MAX],poz[MAX],d[MAX],l;
vector<pair<int,int> > g[MAX];
void swapH(int a,int b){
int aux=heap[a];
heap[a]=heap[b];
heap[b]=aux;
poz[heap[a]]=a;
poz[heap[b]]=b;
}
void upHeap(int k){
while( (k>>1) && d[heap[k>>1]]>d[heap[k]] ){
swapH(k,k>>1);
k>>=1;
}
}
void downHeap(int p){
int q=0;
while(q!=p){
q=p;
if((q<<1)<=l && d[heap[q<<1]] < d[heap[p]] ) p=q<<1;
if((q<<1)+1<=l && d[heap[(q<<1)+1]] < d[heap[p]] ) p=(q<<1)+1;
swapH(p,q);
}
}
void dijkstra(){
for(int i=2;i<=n;i++){
d[i]=INF,poz[i]=-1;
}
poz[1]=1,heap[++l]=1;
while(l){
int min=heap[1];
swapH(1,l);
poz[heap[1]]=1;
l--;
if(l){
downHeap(1);
}
for(iter it=g[min].begin();it!=g[min].end();it++){
if(d[min]+it->second<d[it->first]){
d[it->first]=d[min]+it->second;
if(poz[it->first]!=-1){
upHeap(poz[it->first]);
}else{
heap[++l]=it->first;
poz[heap[l]]=l;
upHeap(l);
}
}
}
}
}
int main(){
FILE* fin=fopen("dijkstra.in","r");
FILE* fout=fopen("dijkstra.out","w");
fscanf(fin,"%d %d\n",&n,&m);
int x,y,c;
for(int i=0;i<=m;i++){
fscanf(fin,"%d %d %d\n",&x,&y,&c);
g[x].push_back(make_pair(y,c));
}
dijkstra();
for(int i=2;i<=n;i++){
fprintf(fout,"%d ",(d[i]==INF)?0:d[i]);
}
fputc('\n',fout);
fclose(fin);
fclose(fout);
return 0;
}