Cod sursa(job #2200760)

Utilizator Dan_RadulescuRadulescu Dan Dan_Radulescu Data 2 mai 2018 15:11:39
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;

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

const int kNmax = 50005;
const int inf = 1000000001;

int n, m, source, d[kNmax], cnt[kNmax];	
vector< pair<int, int> > G[kNmax];
set < pair<int, int> >Q;
set <pair <int,int> >::iterator it;
int main() {
	
	fin >> n >> m;
    for (int i = 1, x, y, w; i <= m; i++) {
        fin >> x >> y >> w;
	    G[x].push_back(make_pair(y, w));
	}
	fin.close();
	
	for (int i = 1; i <= n; i++) {
		    d[i] = inf;
		    cnt[i] = 0;
	}
	d[1] = 0;
		
	int no, dist;
		
	Q.insert(make_pair(0, 1));
	while (!Q.empty()) {
        it = Q.begin();
		no = it->second;
		dist = it->first;
		Q.erase(it);
		for (int i = 0; i < G[no].size(); i++) {
		    int aux = d[G[no][i].first];
		    if (aux > dist + G[no][i].second) {
		        d[G[no][i].first] = dist + G[no][i].second;
		        Q.erase(make_pair(aux, G[no][i].first));
		        Q.insert(make_pair(d[G[no][i].first], G[no][i].first));
		        cnt[G[no][i].first]++;
		        if (cnt[G[no][i].first] >= n) {
		            fout << "Ciclu negativ!\n";
		            fout.close();
		            return 0;
		        }
		    }
		}
	}
		
	for (int i = 2; i <= n; i++)
	    fout << d[i] << " ";
	
	fout.close();
	return 0;
}