Pagini recente » Cod sursa (job #416139) | Cod sursa (job #231073) | Cod sursa (job #34404) | Cod sursa (job #2393202) | Cod sursa (job #2262144)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream f ("dijsktra.in");
ofstream g ("dijsktra.out");
#define GMAX 50010
#define inf 0x3f3f3f3f
#define father(x) (x>>1)
#define left_son(x) (x<<1)
#define right_son(x) ((x<<1) + 1)
struct Heap
{
int nod;
int cost;
}heap[GMAX];
int sz = 0;
vector < pair<int,int> > G[GMAX];
void insert(int nod,int x)
{
sz++;
heap[sz].nod = nod;
heap[sz].cost = x;
int i = sz;
while(father(i) >=1 && heap[father(i)].cost > heap[i].cost)
{
swap(heap[father(i)].cost,heap[i].cost);
swap(heap[father(i)].nod,heap[i].nod);
i=father(i);
}
}
int getNod()
{
return heap[1].nod;
}
int getCost()
{
return heap[1].cost;
}
void pop()
{
heap[1].nod = heap[sz].nod;
heap[1].cost = heap[sz].cost;
sz--;
int i = 1;
while(right_son(i) < sz && (heap[right_son(i)].cost < heap[i].cost || heap[left_son(i)].cost < heap[i].cost))
{
if(heap[right_son(i)].cost < heap[left_son(i)].cost)
{
swap(heap[i].cost,heap[right_son(i)].cost);
swap(heap[i].nod,heap[right_son(i)].nod);
}
else if(heap[right_son(i)].cost > heap[left_son(i)].cost)
{
swap(heap[left_son(i)].cost,heap[i].cost);
swap(heap[left_son(i)].nod,heap[i].nod);
}
i=right_son(i);
}if(left_son(i) < sz && heap[i].cost > left_son(heap[i].cost))
{
swap(heap[i].cost,heap[left_son(i)].cost);
swap(heap[i].nod,heap[left_son(i)].nod);
}
}
int dist[GMAX];
int main()
{
int n,m;
f>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y,z;
f>>x>>y>>z;
G[x].push_back(make_pair(y,z)); // orientat
}
memset(dist,0x3f,sizeof(dist));
int I = 0;
insert(1,0);
while(sz >= 1)
{
int nod = getNod();
int cost = getCost();
pop();
if(dist[nod] != inf)
continue;
dist[nod] = cost;
for(int i=0;i<G[nod].size();i++)
{
insert(G[nod][i].first,cost + G[nod][i].second);
}
}
for(int i=2;i<=n;i++)
{
if(dist[i] == inf) g<<-1<<' ';
else g<<dist[i]<<' ';
}
return 0;
}