Pagini recente » Cod sursa (job #2656760) | Cod sursa (job #520590) | Cod sursa (job #718332) | Cod sursa (job #2516404) | Cod sursa (job #2943221)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");
int n, m, p, x, y, c, v[100001], d[100001];
const int inf = 0x3F3F3F3F;
struct arc {int dest, cost = inf;};
vector<arc> a[100001];
vector<int> heap;
void heapify(int root){
int l = 2*root+1;
int r = 2*root+2;
int minim = root;
if(l<heap.size() && d[heap[l]] < d[heap[minim]]) minim = l;
if(r<heap.size() && d[heap[r]] < d[heap[minim]]) minim = r;
if(minim != root){
swap(heap[root], heap[minim]);
heapify(minim);
}
}
void initial(){for(int i=(heap.size()-1)/2; i>=0; i--) heapify(i);}
void delet(){
swap(heap[0], heap[heap.size()-1]);
heap.pop_back();
if(heap.size()) initial();
}
int main()
{
fin>>n>>m;
for(int i=1; i<=m; i++){
fin>>x>>y>>c;
arc temp;
temp.cost = c;
temp.dest = y;
a[x].push_back(temp);
temp.dest = x;
a[y].push_back(temp);
}
for(int i=1; i<=n; i++){
if(i!=p) heap.push_back(i);
d[i] = inf;
}
for(int i=0; i<a[1].size(); i++)
d[a[1][i].dest] = a[1][i].cost;
v[1] = 1, d[1] = 0;
initial();
while(heap.size()){
int pmin = heap[0];
v[pmin] = 1;
for(int i=0; i<a[pmin].size(); i++){
int dest = a[pmin][i].dest;
int cost = a[pmin][i].cost;
if(!v[dest] && d[dest] > d[pmin] + cost) d[dest] = d[pmin] + cost;
}
delet();
}
for(int i=2; i<=n; i++)
fout<<(d[i]==inf?0:d[i])<<" ";
}