Pagini recente » Cod sursa (job #1247430) | Cod sursa (job #948133) | Cod sursa (job #2821476) | Cod sursa (job #966112) | Cod sursa (job #1378485)
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
#define MAX 50005
#define INF 50000005
struct pereche
{
int nod, cost;
};
vector<pereche> v[MAX];
vector<int> heap;
int n, m, drum[MAX];
void dij(int sursa);
bool comp(int a, int b)
{
return drum[a] < drum[b];
}
int main()
{
freopen("dijkstra.in", "r", stdin);
freopen("dijkstra.out", "w", stdout);
int i, a, b, c;
pereche p;
scanf("%d%d", &n, &m);
for(i=1; i<=m; i++)
{
scanf("%d%d%d", &a, &b, &c);
p.nod = b; p.cost = c;
v[a].push_back(p);
}
dij(1);
for(i=2; i<=n; i++)
printf("%d ", drum[i]);
return 0;
}
void dij(int sursa)
{
int i, fiu, tata, cost;
for(i=1; i<=n; i++)
drum[i] = INF;
drum[sursa] = 0;
heap.push_back(sursa);
make_heap(heap.begin(), heap.end(), comp);
vector<pereche>::iterator it;
while(!heap.empty())
{
tata = heap[0];
pop_heap(heap.begin(), heap.end(), comp);
heap.pop_back();
if(drum[tata] == INF) break;
for(it=v[tata].begin(); it!=v[tata].end(); ++it)
{
fiu = it -> nod; cost = it -> cost;
if(drum[fiu] > drum[tata] + cost){
drum[fiu] = drum[tata] + cost;
heap.push_back(fiu);
push_heap(heap.begin(), heap.end(), comp);
}
}
}
}