Pagini recente » Cod sursa (job #696334) | Cod sursa (job #1504065) | Cod sursa (job #2132699) | Cod sursa (job #3004832) | Cod sursa (job #1547710)
#include <fstream>
#include <algorithm>
#include <vector>
#define pp pair<int,int>
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
const int MaxN = 50001;
const int INF = 1 << 30;
vector < pair < int , int > > G[MaxN];
vector <int> heap;
int d[MaxN],n,m;
bool cmp(const int& a, const int& b)
{
return d[a] > d[b];
}
int main()
{
int x,y,c;
f >> n >> m;
for(int i = 1; i <= m; ++i)
{
f >> x >> y >> c;
G[x].push_back(make_pair(y,c));
}
int source = 1;
for(int i = 2; i <= n; i++) d[i] = INF;
d[source] = 0;
heap.push_back(source);
make_heap(heap.begin(),heap.end(),cmp);
while(heap.size())
{
int node = heap.front();
pop_heap(heap.begin(),heap.end(),cmp);
heap.pop_back();
for(vector<pp>::iterator it = G[node].begin(); it != G[node].end(); ++it)
{
int newNode = it -> first;
int newNodeCost = it -> second;
if(d[newNode] > d[node] + newNodeCost)
{
d[newNode] = d[node] + newNodeCost;
heap.push_back(newNode);
push_heap(heap.begin(),heap.end(),cmp);
}
}
}
for(int i = 2; i <= n; ++i)
g << (d[i] < INF ? d[i] : 0) << " ";
}