Cod sursa(job #2450599)

Utilizator r00t_Roman Remus r00t_ Data 23 august 2019 18:49:23
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <queue>
#include <tuple>
#include <limits>
#include <stdio.h>
#include <string.h>
#include <string>

using namespace std;

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

#define INF 1 << 30

bool processed[100000];
long long dist[100000];
vector<tuple<int, int> >vp[100000];



void dijkstra(int k, int n)
{
	for (int i = 0; i <= n; i++)
		dist[i] = INF;

	priority_queue<pair<int, int> >pq;
	pq.push({ 0,k });
	dist[k] = 0;
	while (!pq.empty())
	{
		k = pq.top().second;
		pq.pop();
		processed[k] = 1;
		for (auto u : vp[k])
		{
			int b, w;
			tie(b, w) = u;
			if (dist[k] + w < dist[b])
				dist[b] = dist[k] + w;
			
			if (processed[b] == 0)
			{
				processed[b] = 1;
				pq.push{ -dist[b], b };
			}
			

		}
	}
}


int main()
{
	int n, m;
	fin >> n >> m;
	for (int i = 0; i < m; i++)
	{
		int a, b, w;
		fin >> a >> b >> w;
		vp[a].push_back({ b,w });
		vp[b].push_back({ a,w });
	}

	dijkstra(1, n);
	for (int i = 2; i <= n; i++) {
		if (dist[i] != INF)
			fout << dist[i] << ' ';
		else fout << 0 << ' ';
	}

}