Pagini recente » Cod sursa (job #1770915) | Cod sursa (job #2440348) | Cod sursa (job #1962951) | Cod sursa (job #1573279) | Cod sursa (job #2645974)
#include <fstream>
#include <vector>
#include <queue>
#include <cassert>
#define NMax 50001
using namespace std;
ofstream fout("dijkstra.out");
class myComparator
{
public:
int operator() (const pair<int, int>& p1, const pair<int, int>& p2)
{
return p1.second > p2.second;
}
};
const int inf = 1 << 30;
int n, m, final_distance[NMax];
vector< pair<int, int> > adj_list[NMax]; // adj_list[node][i] = <other_node, cost>
priority_queue <pair<int, int>, vector< pair<int, int> >, myComparator > pq;
bool visited[NMax];
void read_data()
{
ifstream fin("dijkstra.in");
fin >> n >> m;
int x, y, cost;
for (int i = 1; i <= m; ++i)
{
fin >> x >> y >> cost;
adj_list[x].push_back(make_pair(y, cost));
adj_list[y].push_back(make_pair(x, cost));
}
}
void initialize()
{
// Inserting the source into the priority queue
pq.push(make_pair(1, 0));
final_distance[1] = 0;
// Inserting the other nodes into the pq, initialized with infinity
for (int i = 2 ; i <= n; ++i)
{
final_distance[i] = inf;
pq.push(make_pair(i, inf));
}
}
void Dijsktra()
{
while (!pq.empty())
{
// Get the node with the smallest value associated to it
pair<int, int> current_node;
do
{
current_node = pq.top();
pq.pop();
}
while ( !pq.empty() && visited[current_node.first]);
visited[current_node.first] = true;
for (auto it = adj_list[current_node.first].begin(); it != adj_list[current_node.first].end(); it++)
if (!visited[(*it).first])
{
int alt_dist = current_node.second + (*it).second;
if (alt_dist < final_distance[(*it).first])
{
final_distance[(*it).first] = alt_dist;
pq.push(make_pair((*it).first, alt_dist));
}
}
}
}
void write_data()
{
for (int i = 2; i <= n; ++i)
fout << final_distance[i] << " ";
}
int main()
{
read_data();
initialize();
Dijsktra();
write_data();
return 0;
}