Cod sursa(job #2491638)

Utilizator horiainfoTurcuman Horia horiainfo Data 12 noiembrie 2019 21:30:21
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 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 nodes;			// 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 S to all the other nodes, no negative cycles
void dijkstra(){
    dist = VI(nodes + 1, INF);	// starting at 1
    dist[S] = 0;

    queue<pair<int, int&>> que;
    que.push({S, dist[S]});

    bool inQ[nodes + 1];
    memset(inQ, 0, sizeof(inQ));
    inQ[S] = true;
	
    while(!que.empty()){
        pii p = que.front(); que.pop();
        inQ[p.fi] = false;

        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;

                if(!inQ[e.fi])
                	que.push({e.fi, dist[e.fi]}),
                	inQ[e.fi] = true;
            }
    }
}
	
int main(){
	int m;
	fin >> nodes >> m;

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

	dijkstra();
	for(int i = 2; i <= nodes; i ++)
		if(dist[i] == INF)	fout << "0 ";
		else 				fout << dist[i] << ' ';
}