Cod sursa(job #2645940)

Utilizator ReeeBontea Mihai Reee Data 30 august 2020 11:23:55
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <fstream>
#include <vector>
#include <queue>
#define NMax 50001

using namespace std;

ofstream fout("dijsktra.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("dijsktra.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 = pq.top();
        pq.pop();

        for (auto it = adj_list[current_node.first].begin(); it != adj_list[current_node.first].end(); it++)
        {
            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;
}