Cod sursa(job #1826358)

Utilizator msciSergiu Marin msci Data 10 decembrie 2016 12:59:24
Problema Algoritmul lui Dijkstra Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>

using namespace std;

struct Edge;
struct Node
{
    vector<Edge> adj;
    Node* parent;
    int dist;
    Node() { dist = INT_MAX; }
};

struct Edge
{
    int target, weight;
};

int N, M;
Node V[50005];

void dijkstra(int source)
{
    V[source].dist = 0;
    typedef pair<int, int> P;
    priority_queue<P, vector<P>, greater<P> > heap;
    heap.push({source, 0});
    while (!heap.empty())
    {
	P current = heap.top();
	heap.pop();
	if (current.second != V[current.first].dist) continue;
	for (auto edge : V[current.first].adj)
	{
	    int new_dist = current.second + edge.weight;
	    if (V[edge.target].dist > new_dist)
	    {
		V[edge.target].dist = new_dist;
		heap.push({edge.target, new_dist});
	    }
	}
    }
}

int main()
{
    freopen("dijkstra.in", "r", stdin);
    freopen("dijkstra.out", "w", stdout);
    scanf("%d %d", &N, &M);
    for (int i = 0; i < M; i++)
    {
	int x, y, w;
	scanf("%d %d %d", &x, &y, &w);
	Edge e;
	e.target = y;
	e.weight = w;
	V[x].adj.push_back(e);
    }
    dijkstra(1);
    for (int i = 2; i <= N; i++)
    {
	if (V[i].dist == INT_MAX) printf("0 ");
	else printf("%d ", V[i].dist);
    }
    printf("\n");
}