Cod sursa(job #1826333)

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

using namespace std;

struct Edge
{
    int target, weight;
};

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

struct Order
{
    bool operator()(const pair<int, int>& a, const pair<int, int>& b)
    {
	return a.first < b.first;
    }
};

int N, M;
Node V[50005];

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

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++)
    {
	printf("%d ", V[i].dist);
    }
    printf("\n");
}