Cod sursa(job #2723287)

Utilizator UnknownPercentageBuca Mihnea-Vicentiu UnknownPercentage Data 13 martie 2021 20:43:55
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <bits/stdc++.h>
 
using namespace std;

ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

const int INF = 1e9;

vector <pair <int, int>> Gr[50001];

bitset <50001> u;
int d[50001], cnt[50001];
int N, M;

void SPFA(int s){
	for(int i = 1;i <= N;i++)
		d[i] = INF;

	queue <int> q;
	q.push(s);
	u[s] = 1, d[s] = 0;

	while(!q.empty()){
		int v = q.front();
		q.pop();
		u[v] = 0;

		for(auto edge : Gr[v]){
			int to = edge.first;
			int len = edge.second;

			if(d[v] + len < d[to]){
				d[to] = d[v] + len;
				if(!u[to]){
					if(++cnt[to] > N){
						g << "Ciclu Negativ";
						exit(0);
					}

					q.push(to);
					u[to] = 1;
				}
			}
		}
	}

	for(int i = 1;i <= N;i++)
		if(i != s) g << d[i] << " ";
}

int main(){

	f >> N >> M;
	while(M--){
		int x, y, c;
		f >> x >> y >> c;
		Gr[x].emplace_back(y, c);
	}

	SPFA(1);
}