Cod sursa(job #2714006)

Utilizator UnknownPercentageBuca Mihnea-Vicentiu UnknownPercentage Data 1 martie 2021 08:31:01
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>
 
using namespace std;
 
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

const int INF = 1e9;

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

bitset <50001> u;

int d[50001], cnt[50001];
int N, M, Q;

void SPFA(int s){
    queue <int> q;
    for(int i = 1;i <= N;i++)
        d[i] = INF;
    
    d[s] = 0, u[s] = 1;
    q.push(s);
    while(!q.empty()){
        int v = q.front();
        q.pop();
        u[v] = 0;
        for(auto edge : adj[v]){
            int to = edge.first;
            int len = edge.second;

            if(d[v] + len < d[to]){
                d[to] = d[v] + len;
                if(!u[to]){
                    q.push(to);
                    u[to] = 1;
                    cnt[to]++;
                    if(cnt[to] > N){
                    	g << "Ciclu negativ!";
                    	return;
                    }
                }
            }
        }
    }

    for(int i = 2;i <= N;i++)
    	g << d[i] << " ";
}

int main(){

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

	SPFA(1);
}