Cod sursa(job #1419934)

Utilizator flore77Simion Florentin flore77 Data 17 aprilie 2015 09:36:34
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <utility>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <set>
#include <algorithm>
using namespace std;

#define BIG 99999999
#define MAXN 5000

int **graph;
int dist[MAXN], visited[MAXN], n;

int minim() {
    int i, min = BIG, poz = -1;

    for (i = 1; i <= n; i++) {
        if (dist[i] < min && !visited[i]) {
            min = dist[i];
            poz = i;
        }
    }
    if (poz != -1)
        visited[poz] = 1;
    return poz;
}

int main() {

    ifstream in("dijkstra.in");
    int m;

    in >> n >> m;
    graph = new int*[n + 1];

    for (int i = 0; i < n + 1; i++) {
        graph[i] = new int[n];
    }

    int edge1, cost, edge2;


    for (int i = 0; i < m; i++) {
        in >> edge1 >> edge2 >> cost;
        graph[edge1][edge2] = cost;
        graph[edge2][edge1] = cost;
    }

    in.close();

    for (int i = 2; i <= n; i++) {
        dist[i] = BIG;
        visited[i] = 0;
    }

    dist[1] = 0;
    int poz;

    while ((poz = minim()) != -1) {

        for (int j = 1; j <= n; j++) {
            if (graph[poz][j] != 0) {
                if (dist[poz] + graph[poz][j] < dist[j]) {
                    dist[j] = dist[poz] + graph[poz][j];
                }
            }
        }
    }

    ofstream out("dijkstra.out");
    for (int i = 2; i <= n; i++) {
        if (dist[i] == BIG)
            out << 0 << " ";
        else
            out << dist[i] << " ";
    }
    return 0;
}