Cod sursa(job #1012768)

Utilizator sziliMandici Szilard szili Data 19 octombrie 2013 16:49:29
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <iostream>
#include <queue>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <vector>

using namespace std;

typedef struct nodeType {
    int node;
    int cost;

    const bool operator < (const nodeType &other) const {
        return cost > other.cost;
    }

} NODE;

//on position i, we have another vector with all the neighbors of i.
vector<NODE> adjacencyList[50001];
int solutions[50001];
int visited[50001];

int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);

    int n,m;
    scanf("%d %d", &n, &m);

    int node1, node2, cost;


    for (int i=0; i<m; i++){
        scanf("%d %d %d", &node1, &node2, &cost);
        NODE n1,n2;
        n1.node = node1;
        n1.cost = cost;

        n2.node = node2;
        n2.cost = cost;

        adjacencyList[node1].push_back(n2);
        adjacencyList[node2].push_back(n1);
    }

    priority_queue<NODE> heap;

    NODE firstNode;
    firstNode.node = 1;
    firstNode.cost = 0;


    heap.push(firstNode);

    int currentNode;
    while (!heap.empty()){

        if (!visited[heap.top().node]){
            currentNode = heap.top().node;
            visited[currentNode] = 1;
            solutions[currentNode] = heap.top().cost;

            for (vector<NODE>::iterator nodeIT = adjacencyList[currentNode].begin(); nodeIT != adjacencyList[currentNode].end(); nodeIT++){
                if (!visited[nodeIT->node]) {
                    NODE newNode;
                    newNode.node = nodeIT->node;
                    newNode.cost = heap.top().cost + nodeIT->cost;

                    heap.push(newNode);
                }
            }
        }
        heap.pop();
    }

    for (int i=2; i<=n; i++){
        printf("%d ", solutions[i]);
    }

    return 0;
}