Cod sursa(job #1983168)

Utilizator FrequeAlex Iordachescu Freque Data 21 mai 2017 13:17:46
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.34 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

struct edge
{
    int nod;
    int cost;

    edge(int init_nod, int init_cost)
    {
        nod = init_nod;
        cost = init_cost;
    }
};

const int NMAX = 50000 + 5;
const int INF = 0x3f3f3f3f;

vector <edge> g[NMAX];
queue <int> q;

int n, m;
int drum[NMAX], cnt[NMAX];
bool vis[NMAX];

void read()
{
    int x, y, c;
    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        fin >> x >> y >> c;
        g[x].push_back(edge(y, c));
    }
}

void init(int node)
{
    for (int i = 1; i <= n; ++i)
        drum[i] = INF;
    drum[node] = 1;
}

int bellman_ford(int nod)
{
    q.push(nod);
    vis[nod] = 1;
    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        vis[nod] = 0;
        for (vector<edge>::iterator it = g[nod].begin(); it != g[nod].end(); ++it)
            if (drum[it -> nod] > drum[nod] + it -> cost)
            {
                drum[it -> nod] = drum[nod] + it -> cost;
                if (!vis[it -> nod])
                {
                    if (++cnt[it -> nod] == n)
                        return 0;
                    q.push(it -> nod);
                    vis[it -> nod] = 1;
                }
            }
    }
    return 1;
}

bool bellman(int node)
{
    int x;
    for (int i = 1;i <= n; ++i)
        drum[i] = INF;
    drum[node] = 0;
    q.push(node);
    vis[node] = true;
    while (!q.empty())
    {
        x = q.front();
        q.pop();
        vis[x] = false;
        for (int i = 0; i < g[x].size(); ++i)
            if (drum[g[x][i].nod] > drum[x] + g[x][i].cost)
            {
                drum[g[x][i].nod] = drum[x] + g[x][i].cost;
                if (!vis[g[x][i].nod])
                {
                    if (++cnt[g[x][i].nod] == n)
                        return 0;
                    q.push(g[x][i].nod);
                    vis[g[x][i].nod] = true;
                }
            }
    }
    return 1;
}

void write()
{
    if (bellman(1))
        for (int i = 2; i <= n; ++i)
            fout << drum[i] << " ";
    else
        fout << "Ciclu negativ!";
}

int main()
{
    read();
    write();

    return 0;
}