Cod sursa(job #2563565)

Utilizator ionita786Ionita Daniel ionita786 Data 1 martie 2020 12:32:04
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int n,m,viz[50001],nod;
int wnode[50001];
queue <int> q;
vector < pair <int,int> > edge[50001];
bool coada[50001];
int main()
{
    ios_base::sync_with_stdio(0);
    in.tie(0);
    in >> n >> m;
    for(int i = 1; i <= m ; ++i)
    {
        int a,b,cost;
        in >> a >> b >> cost;
        edge[a].push_back({b,cost});
    }
    memset(wnode, '1001', sizeof(wnode));
    wnode[1] = 0;
    q.push(1);
    while(!q.empty())
    {
        nod = q.front();
        viz[nod] ++;
        if(viz[nod] == n)
        {
            out << "Ciclu negativ!";
            return 0;
        }
        coada[nod] = 0;
        q.pop();
         for(int i = 0; i < edge[nod].size(); ++i)
            {
                int neighbour = edge[nod][i].first;
                int weight = edge[nod][i].second;
                if(wnode[neighbour] > wnode[nod] + weight)
                {
                    wnode[neighbour] = wnode[nod] + weight;
                    if(!coada[neighbour])
                    {
                        q.push(neighbour);
                        coada[neighbour] = 1;
                    }
                }
            }
    }
    for(int i = 2; i <= n; ++i)
        out << wnode[i] << " ";
    return 0;
}