Pagini recente » Cod sursa (job #1187110) | Cod sursa (job #2871456) | Cod sursa (job #2207439) | Cod sursa (job #2710688) | Cod sursa (job #735988)
Cod sursa(job #735988)
#include <fstream>
#include <iostream>
#include <vector>
#define nmax 50005
#define x first
#define y second
using namespace std;
int n, m, d[nmax], heap[nmax], n_heap, poz[nmax];
vector<pair<int,int> > gf[nmax];
int N;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
void citeste(){
f >> N >> m;
for(int i=1; i<=m; i++){
int x, y, c;
f >> x >> y >> c;
gf[x].push_back(make_pair(y,c));
}
}
void in_jos(int nod){
for(int ok=1; ok; ){
int nod_min = nod;
if (nod*2 <= n_heap && d[heap[nod*2]] < d[heap[nod_min]]) nod_min = nod*2;
if (nod*2+1 <= n_heap && d[heap[nod*2+1]] < d[heap[nod_min]]) nod_min = nod*2+1;
if (nod_min == nod) break;
swap(poz[heap[nod]], poz[heap[nod_min]]);
swap(heap[nod], heap[nod_min]);
nod = nod_min;
}
}
void in_sus(int nod){
for(; nod != 1; ){
if (nod > 1 && d[heap[nod]] < d[heap[nod/2]]){
swap(poz[heap[nod]], poz[heap[nod/2]]);
swap(heap[nod], heap[nod/2]);
nod = nod/2;
}
else nod = 1;
}
}
void rezolva(){
for(int i=2; i<=N; i++) d[i] = (1<<30), poz[i] = -1;
poz[1] = 1;
heap[++n_heap] = 1;
for(; n_heap; ){
int nod = heap[1];
//poz[heap[1]] = 1;
swap(poz[heap[1]], poz[heap[n_heap]]);
swap(heap[1], heap[n_heap]);
--n_heap;
in_jos(1);
for(int i=0; i<gf[nod].size(); i++){
int vc = gf[nod][i].x;
int cost = gf[nod][i].y;
if (d[vc] > d[nod] + cost){
d[vc] = d[nod] + cost;
if (poz[vc] == -1){
heap[++n_heap] = vc;
poz[heap[n_heap]] = n_heap;
in_sus(n_heap);
}else{
in_sus(poz[vc]);
}
}
}
}
}
int main(){
citeste();
rezolva();
for(int i=2; i<=N; i++) if (d[i] == (1<<30)) g << 0 << " ";
else g << d[i] << " ";
f.close();
g.close();
return 0;
}