Cod sursa(job #3256226)

Utilizator Tudor.1234Holota Tudor Matei Tudor.1234 Data 13 noiembrie 2024 20:57:32
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include "bits/stdc++.h"
#define int long long int
#define inf  INT_MAX
const int SIZE = 50000;
std :: vector < std :: vector < std :: pair < int, int > > > adj;
std :: queue < int > q;
int dist[SIZE + 5], n, m;
bool vis[SIZE + 5];
void Init(){
	for(int i = 0; i <= SIZE + 1; i++){
		dist[i] = inf;
	}
}
void BellmanFord(int root){
	vis[root]  = true;
	dist[root] = 0;
	q.push(root);
	while(!q.empty()){
		int current = q.front();
		vis[current] = false;
		q.pop();
		for(int i = 0; i < adj[current].size(); i++){
			int node = adj[current][i].first;
			int cost = adj[current][i].second;
			if(dist[node] > dist[current] + cost){
				dist[node] = dist[current] + cost;
				if(!vis[node]){
					q.push(node);
					vis[node] = true;
				}
			}
		}
	}
}
void Solve(){
	std :: cin >> n >> m;
	adj.resize(n + 1);
	for(int i = 1; i <= m; i++){
		int x, y, cost;
		std :: cin >> x >> y >> cost;
		adj[x].push_back({y, cost});
	}
	Init();
	BellmanFord(1);
	for(int i = 2; i <= n; i++){
		std :: cout << dist[i] << ' ';
	}
}
signed main(){
	freopen("bellmanford.in", "r", stdin);
	freopen("bellmanford.out", "w", stdout);
	std :: ios_base :: sync_with_stdio(false);
	std :: cin.tie(0);
	std :: cout.tie(0);
	Solve();
	return 0;
}