Cod sursa(job #2187649)

Utilizator killer301Ioan Andrei Nicolae killer301 Data 26 martie 2018 17:42:31
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

const int NMAX = 50000;
const int INF = 2000000000;

int n;

vector <pair <int, int> > g[NMAX+5];
bool in_queue[NMAX+5];
int vis[NMAX+5];
int dist[NMAX+5];

void Bellman_ford(int nod)
{
    queue <int> q;
    dist[nod] = 0;
    q.push(nod);
    in_queue[nod] = true;
    while(!q.empty())
    {
        int top = q.front();
        q.pop();
        in_queue[top] = false;
        for(int i=0; i<g[top].size(); i++)
        {
            pair <int, int> New = g[top][i];
            if(dist[top] + New.second < dist[New.first])
            {
                dist[New.first] = dist[top] + New.second;
                if(!in_queue[New.first])
                {
                    if(vis[New.first] > n)
                    {
                        printf("Ciclu negativ!\n");
                        return;
                    }
                    in_queue[New.first] = true;
                    q.push(New.first);
                    vis[New.first]++;
                }
            }
        }
    }
    for(int i=2; i<=n; i++)
        printf("%d ", dist[i]);
    printf("\n");
}

int main()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    int m;
    scanf("%d%d", &n, &m);
    for(int i=0; i<m; i++)
    {
        int x, y, c;
        scanf("%d%d%d", &x, &y, &c);
        g[x].push_back(pair <int, int> (y, c));
    }

    for(int i=1; i<=n; i++)
        dist[i] = INF;
    Bellman_ford(1);
    return 0;
}