Cod sursa(job #2491625)

Utilizator horiainfoTurcuman Horia horiainfo Data 12 noiembrie 2019 21:16:06
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>
#define N 50005

#define pb push_back
#define fi first
#define se second
#define pii pair<int, int>
#define VI vector<int>

using namespace std;

const int INF = 0x3f3f3f3f;
	
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

int n;				// number of nodes (read it)
int S = 1;			// the starting node
vector<pii> g[N]; 	// fi = next node, se = distance
VI dist;

// Computes the distance from 0 to all the other nodes, works with negative distances
void dijkstra(){
    queue<pii> que;
    dist = VI(n + 1, INF);	// starting at 1
    dist[S] = 0;
    que.push({S, 0});
	
    while(!que.empty()){
        pii p = que.front(); que.pop();
        if(p.se != dist[p.fi]) continue;

        for(pii e : g[p.fi])
            if(p.se + e.se < dist[e.fi]){
                dist[e.fi] = p.se + e.se;
                que.push({e.fi, dist[e.fi]});
            }
    }
}
	
int main(){
	int m;
	fin >> n >> m;

	while(m --){
		int x, y, d;
		fin >> x >> y >> d;
		g[x].pb({y, d});
		g[y].pb({x, d});
	}

	dijkstra();
	for(int i = 2; i <= n; i ++)
		fout << dist[i] << ' ';
}