Cod sursa(job #2181635)

Utilizator VarticeanNicolae Varticean Varticean Data 21 martie 2018 19:31:18
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
#define nmax 50005
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
vector < pair < int, int >> v[nmax];
int dist[nmax],n,m,viz[nmax];
void read()
{
   in >> n >> m;
   int x,y,c;
   for(int i=1; i<=m; i++)
   {
       in >> x >> y >> c;
       v[x].push_back({y,c});
   }
   for(int i=2; i<=n; i++) dist[i] = 1 << 30;
}
int main()
{
    ios::sync_with_stdio(0);
    read();
    queue < int > q;
    viz[1] = 1;
    q.push(1);
    while ( !q.empty() )
    {
        int head = q.front();
        q.pop();
        viz[head]++;
        if( viz[head] == n  ) return out <<"Ciclu negativ!", 0;
        for(int i=0; i<v[head].size(); i++)
        {
           int j = v[head][i].first;
           int cost = v[head][i].second;

           if( dist[j] > dist[head] + cost )
           {
               dist[j] = dist[head] + cost;
               q.push(j);
           }
        }
    }
    for(int i=2; i<=n; i++) out << dist[i] << ' ';


    return 0;
}