Cod sursa(job #2336692)

Utilizator RK_05Ivancu Andreea Raluca RK_05 Data 5 februarie 2019 14:04:11
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <climits>
#include <vector>
#define nmax 50005
#define mmax 250005

using namespace std;

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

int n, m, dist[nmax], a[nmax];
const int inf = INT_MAX;
vector < pair <int,int> > G[nmax];

void read(){
    int x, y, c;
    fin >> n >> m;
    for(int i = 1; i <= m; ++i){
        fin >> x >> y >> c;

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

void dijkstra(int source){
    int e = 0;
    for(int i = 1; i <= n; ++i)
        if(a[i] == 0){
            e = 1;
            break;
        }
    if(e == 0)
        return;
    else{
        for(int i = 0; i < G[source].size(); ++i){
            if(dist[G[source][i].first] > dist[source] + G[source][i].second && a[G[source][i].first] == 0)
                dist[G[source][i].first] = dist[source] + G[source][i].second;
        }
        int mini = inf, ind;
        for(int i = 1; i <= n; ++i){
            if(dist[i] < mini && a[i] == 0){
                mini = dist[i];
                ind = i;
            }
        }
        a[ind] = 1;
        dijkstra(ind);
    }
}

void sol(){
    for(int i = 2; i <= n; ++i){
        fout << dist[i] << " ";
    }
}

int main(){

    read();
    for(int i = 2; i <= n; ++i){
        dist[i] = inf;
    }
    dist[1] = 0;
    a[1] = 1;
    dijkstra(1);
    sol();
    return 0;
    fin.close();
}