Cod sursa(job #1632112)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 5 martie 2016 21:31:54
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <vector>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;

ifstream is("bellmanford.in");
ofstream os("bellmanford.out");

using VI = vector<int>;
using VVI = vector<VI>;
using VP = vector<pair<int, int>>;
using VVP = vector<VP>;
using VPP = vector<pair<int, pair<int, int>>>;

int n, m;
VI d, cnt;
VVP g;
queue<int> q;

void Read();

int main()
{
    Read();
    is.close();
    d = VI(n + 1, INF);
    cnt = VI(n + 1);
    d[1] = 0;
    q.push(1);
    int nod;
    while ( q.size() )
    {
        nod = q.front();
        q.pop();
        ++cnt[nod];
        if ( cnt[nod] == n )
        {
            os << "Ciclu negativ!";
            os.close();
            return 0;
        }
        for ( const auto &nodv : g[nod] )
            if ( d[nodv.second] > d[nod] + nodv.first )
            {
                d[nodv.second] = d[nod] + nodv.first;
                q.push(nodv.second);
            }
    }
    for ( int i = 2; i <= n; ++i )
        os << ( d[i] == INF ? 0 : d[i] ) << " ";
    os.close();
    return 0;
}

void Read()
{
    is >> n >> m;
    g = VVP(n + 1);
    int x, y, z;
    for ( int i = 1; i <= m; ++i )
    {
        is >> x >> y >> z;
        g[x].push_back(make_pair(z, y));
    }
}