Cod sursa(job #2419365)

Utilizator Teo_1101Mititelu Teodor Teo_1101 Data 8 mai 2019 11:40:10
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb

#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream fin("dijkstra2.in");
ofstream fout("dijkstra2.out");

const int NMAX = 100001;
const int INF = 2000000000;

int N, M, P;

bool vis[NMAX];
int dist[NMAX];

vector < pair < int, int > > Ad[NMAX];
priority_queue < pair < int, int > > H;

void Read()
{
    fin >> N >> M;

    int x, y, c;
    for( int i = 1; i <= M; ++i )
    {
        fin >> x >> y >> c;

        Ad[x].push_back( make_pair( y, c ) );
        Ad[y].push_back( make_pair( x, c ) );
    }

    for( int i = 1; i <= N; ++i ) dist[i] = INF;
}

void Dijkstra( int x )
{
    dist[x] = 0;

    H.push( make_pair( 0, x ) );

    while( H.size() )
    {
        int nod = H.top().second;
        int d = H.top().first;

        H.pop();

        if( !vis[nod] )
        {
            vis[nod] = 1;
        for( int i = 0; i < Ad[nod].size(); ++i )
        {
            pair < int, int > w = Ad[nod][i];

            if( dist[w.first] > d + w.second )
            {
                dist[w.first] = d + w.second;
                H.push( make_pair( dist[w.first], w.first ) );
            }
        }

        }
    }

    for( int i = 2; i <= N; ++i )
        fout << dist[i] << ' ';
}
int main()
{
    Read();
    Dijkstra( 1 );
    return 0;
}