Pagini recente » Cod sursa (job #524296) | Cod sursa (job #2898174) | Cod sursa (job #1964825) | Cod sursa (job #1044755) | Cod sursa (job #388159)
Cod sursa(job #388159)
#include<fstream>
#define inf "dijkstra.in"
#define outf "dijkstra.out"
#define NMax 50010
#define INF 0x3f3f3f3f
using namespace std;
fstream f(inf,ios::in),g(outf,ios::out);
struct graf
{
int nod,cost;
graf *next;
};
int N,M;
graf *a[NMax];
int d[NMax],s[NMax];
int heap[NMax];//heap[i]=j <=> eticheta nodului i din heap este nodul j din graf
int pos[NMax];//pos[i]=j <=> nodul i din graf se afla pe nodul j din heap
int dim;
void add(int unde,int nd,int cst)
{
graf *c=new graf;
c->nod=nd;
c->cost=cst;
c->next=a[unde];
a[unde]=c;
}
void Citire()
{
int x,y,z;
f>>N>>M;
for(int i=1;i<=M;i++)
{
f>>x>>y>>z;
add(x,y,z);
}
for(int i=1;i<=N;i++){d[i]=INF;pos[i]=-1;}
}
int father(int nodh){return nodh/2;}
int lson(int nodh){return nodh*2;}
int rson(int nodh){return nodh*2+1;}
void upheap(int nodh)
{
int tata;
tata=father(nodh);
while(tata>1)
{
if(d[heap[nodh]]<d[heap[tata]])
{
swap(pos[heap[nodh]],pos[heap[tata]]);
swap(heap[nodh],heap[tata]);
nodh=tata;
tata=father(nodh);
}
else break;
}
}
void downheap(int nodh)
{
int son=0;
do
{
son=0;
if(lson(nodh)<=dim)
{
son=lson(nodh);
if(rson(nodh)<=dim && d[heap[son]]>d[heap[rson(nodh)]])son=rson(nodh);
if(d[heap[son]]<d[heap[nodh]])
{
swap(pos[heap[son]],pos[heap[nodh]]);
swap(heap[son],heap[nodh]);
nodh=son;
}
else son=0;
}
}
while(son);
}
void cut(int nodh)
{
swap(pos[heap[nodh]],pos[heap[dim]]);
swap(heap[nodh],heap[dim]);
dim--;
downheap(nodh);
//cernem nodul, deoarece procedura cut va fi apelata doar pentru primul nod din heap
}
void insert(int nodg)
{
heap[++dim]=nodg;
pos[nodg]=dim;
upheap(dim);
}
void Dijkstra()
{
int min;
d[1]=0;
pos[1]=1;
heap[++dim]=1;
while(dim)
{
min=heap[1];
cut(1);
graf *t=a[min];
while(t)
{
if(d[t->nod]>d[min]+t->cost)
{
d[t->nod]=d[min]+t->cost;
if(pos[t->nod]!=-1)upheap(pos[t->nod]);
else insert(t->nod);
}
t=t->next;
}
}
}
void Afisare()
{
for(int i=2;i<=N;i++)
{
if(d[i]==INF)g<<"0 ";
else g<<d[i]<<" ";
}
}
int main()
{
Citire();
Dijkstra();
Afisare();
f.close();
g.close();
return 0;
}