Cod sursa(job #1307559)

Utilizator BlackBird_v.1.0Stephen Berg BlackBird_v.1.0 Data 2 ianuarie 2015 15:56:15
Problema Sate Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.77 kb
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define Nmax 30013
#define inf 20*1000000
#define nod first
#define l64 long long
#define cost second
vector < pair < int, int > > G[Nmax];
int i,j,n,m,a,b,c,lheap(0),x,y;
l64 D[Nmax];
bool used[Nmax];
l64 Heap[Nmax];
int poz[Nmax];

void heap_down(int nod,int lheap)
 {
  int fiu=nod*2;
  if (fiu>lheap) return ;
  if (fiu<lheap && D[Heap[fiu]]>D[Heap[fiu+1]]) ++fiu;	   
  if (D[Heap[fiu]]<D[Heap[nod]]) 
	 {
	  swap(poz[Heap[fiu]],poz[Heap[nod]]);
	  swap(Heap[fiu],Heap[nod]);
	  heap_down(fiu,lheap);
	 }
 }

void heap_up(int nod)
{
 int father=nod/2;
 if (!father) return;
 if (D[Heap[nod]]<D[Heap[father]])
      {
       swap(poz[Heap[nod]],poz[Heap[father]]);
       swap(Heap[nod],Heap[father]);
       heap_up(father);
	  }
}

void add_heap(int value)
{  
 ++lheap;
 Heap[lheap]=value;
 poz[value]=lheap;
 heap_up(lheap);
}

void erase_top(int &lheap)
{
 swap(poz[Heap[1]],poz[Heap[lheap]]);
 swap(Heap[1],Heap[lheap]);
 --lheap;
 heap_down(1,lheap);
}

void dijkstra(int nod)
{
 for (int i=1;i<=n;++i) 
    {
	if (i==x) D[i]=0; 
	     else D[i]=inf;          //initializam heapul
    add_heap(i);
    }
    
while(lheap>0)
   {
   	int virf=Heap[1];
   	erase_top(lheap);
   	for (int i=0;i<G[virf].size();++i)
   	   {
   	   	if (D[G[virf][i].nod]>D[virf]+G[virf][i].cost)
   	   	     {
   	   	      D[G[virf][i].nod]=D[virf]+G[virf][i].cost;
   	   	      heap_up(poz[G[virf][i].nod]);
			 }
	   }	
   }	
}

int main(void)
{
 ifstream in("sate.in");
 ofstream out("sate.out");
 in>>n>>m>>x>>y;
 while(m--)
  {
   in>>a>>b>>c;
   G[a].pb(mp(b,c));
   G[b].pb(mp(a,-1*c));
  }
dijkstra(x);
out<<D[y];
return 0;
}