Cod sursa(job #3220557)

Utilizator alexvali23alexandru alexvali23 Data 4 aprilie 2024 09:25:40
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <vector>
#include <queue>
#define Nmax 500002
#define INF 1e9
using namespace std;

ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

int n, m;
vector<pair<int, int>> mat[Nmax];
queue<int> q;
vector<int> dist(Nmax, INF);
int viz[Nmax], cnt[Nmax];

void Bellman_Ford()
{
    dist[1] = 0;
    q.push(1);
    while(!q.empty())
    {
        int k = q.front();
        q.pop();
        viz[k] = 0;
        for(auto it : mat[k])
        {
            int cost = it.second;
            int dest = it.first;
            if(dist[k] + cost < dist[dest])
            {
                dist[dest] = dist[k] + cost;
                if(viz[dest] == 0)
                {
                    viz[dest] = 1;
                    q.push(dest);
                    cnt[dest]++;
                    if(cnt[dest] > n)
                    {
                        g << "Ciclu negativ!";
                        exit(0);
                    }
                }
            }
        }
    }
}

int main()
{
    f >> n >> m;
    int a, b, c;
    for(int i = 1; i <= m; i++)
    {
        f >> a >> b >> c;
        mat[a].push_back({b, c});
    }
    for(int i = 1; i <= n; i++)
        dist[i] = INF;
    Bellman_Ford();
    for(int i = 2; i <= n; i++)
        g << dist[i] << ' ';
}