Cod sursa(job #2373290)

Utilizator pistvanPeter Istvan pistvan Data 7 martie 2019 13:00:09
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#include <limits.h>
#include <set>
#include <vector>
#define INF INT_MAX
#define MAXN 50001

using namespace std;

int N, M;
bool vis[MAXN];
int dist[MAXN];
vector<pair<int,int>> G[MAXN];//adjacency list with vertex-weight pairs
//G[a][0].first contains the number of neighbours of a
set<pair<int,int>> S; //a set of distance-node pairs

void Read()
{
    ifstream f("dijkstra.in");
    f>>N>>M;
    for (int i=1;i<=N;i++)
    {
        G[i].push_back({0, 0});
        dist[i]=(i==1)?0:INF;
        S.insert({dist[i], i});
    }
    int a, b, c;
    for (int i=1;i<=M;i++)
    {
        f>>a>>b>>c;
        G[a].push_back({b, c});
        G[a][0].first++;
    }
}

void Dijkstra()
{
    int source, index=N, nextnode;
    while (--index)
    {
        source=S.begin()->second;
        if (dist[source]==INF)
            break;
        for (int i=1;i<=G[source][0].first;i++)
        {
            nextnode=G[source][i].first;
            if (vis[nextnode])
                continue;
            if (dist[nextnode]==INF || (dist[nextnode]!=INF && dist[nextnode]>dist[source]+G[source][i].second))
            {
                // cout<<"Node "<<nextnode<<" optimized with "<<source<<" to ";
                S.erase(S.find({dist[nextnode], nextnode}));
                dist[nextnode]=dist[source]+G[source][i].second;
                //cout<<dist[nextnode]<<'\n';
                S.insert({dist[nextnode], nextnode});
            }
        }
        vis[source]=1;
        S.erase(S.find({dist[source], source}));
    }
}

void Write()
{
    ofstream g("dijkstra.out");
    for (int i=2;i<=N;i++)
        if (dist[i]==INF)
            g<<0<<' ';
        else
            g<<dist[i]<<' ';
}

int main()
{
    Read();
    Dijkstra();
    Write();
}