Cod sursa(job #2867078)

Utilizator Max_CalincuMaxim Calincu Max_Calincu Data 10 martie 2022 10:45:20
Problema Algoritmul Bellman-Ford Scor 45
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
using namespace std;
 
typedef long long ll;
#define f first
#define s second
#define pb push_back
#define mp make_pair
#define pi pair<ll, ll>
#define sz(x) (int)((x).size())
#define all(a) (a).begin(), (a).end()

/*const ll maxn = 1e5;
int f[maxn],nf[maxn],inv[maxn];
const int M=998244353;
void init(){
    inv[1]=1; for (int i=2;i<maxn;i++) inv[i]=M-1ll*(M/i)*inv[M%i]%M;
    f[0]=nf[0]=1; for (int i=1;i<maxn;i++) f[i]=1ll*f[i-1]*i%M,nf[i]=1ll*nf[i-1]*inv[i]%M;
}
int C(int x,int y){return 1ll*f[x]*nf[y]%M*nf[x-y]%M;} */

const ll mod = 1e9+7;
ll n, k, m, mi, ma;

void solve(){
	
	ifstream cin("bellmanford.in");
	ofstream cout("bellmanford.out");
	
	
	cin >> n >> m;
	vector<pi> a[n + 5];
	for(int i = 0; i<m; i++){
		ll x, y, c;
		cin >> x >> y >> c;
		x--; y--;
		a[x].pb({y, c});
	}
	queue<pi> q;
	q.push({0, 1});
	vector<ll> d(n, mod);
	d[0] = 0;
//	vector<bool> v(n, 0);
//	v[0] = 1;
	while(!q.empty()){
		pi r = q.front();
		q.pop();
		if(r.s == n + 1){
			cout << "Ciclu negativ!\n";
			return;
		}
		ll x = r.f;
//		v[x] = 0;
		for(int i = 0; i<a[x].size(); i++){
			ll y = a[x][i].f, c = a[x][i].s;
			if(d[x] + c >= d[y]) continue;
			//if(v[y] == 0){
//				v[y] = 1;
				q.push({y, r.s + 1});
			//}
			d[y] = d[x] + c;
		}
	}
	
	for(int i = 1; i<n; i++) cout << d[i] << " "; cout << "\n";
	 
	

}

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);

	//init();
	
	int t=1;
//	cin >> t;
	while(t--) solve();
	
	return 0;
}