Cod sursa(job #1469103)

Utilizator tudormaximTudor Maxim tudormaxim Data 7 august 2015 16:22:20
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int nmax = 50005;
vector < pair<int,int> > graf[nmax];
int n, m, d[nmax], nrq[nmax];
bool viz[nmax];
void bellmanford()
{
    int i, nod;
    queue <int> q;
    vector <pair<int,int> >::iterator it;
    for(i=2; i<=n; i++)
        d[i]=1<<30;
    q.push(1);
    while(!q.empty())
    {
        nod=q.front();
        q.pop();
        viz[nod]=false;
        for(it=graf[nod].begin(); it!=graf[nod].end(); it++)
            if(d[it->first] > d[nod]+it->second)
            {
                d[it->first]=d[nod]+it->second;
                if(!viz[it->first])
                {
                    if(nrq[it->first]>n)
                    {
                        fout << "Ciclu negativ!";
                        return;
                    }
                    nrq[it->first]++;
                    viz[it->first]=true;
                    q.push(it->first);
                }
            }
    }
    for(i=2; i<=n; i++)
        fout << d[i] << " ";
}
int main()
{
    int x, y, c, i;
    fin >> n >> m;
    for(i=1; i<=m; i++)
    {
        fin >> x >> y >> c;
        graf[x].push_back(make_pair(y, c));
    }
    bellmanford();
    fin.close();
    fout.close();
    return 0;
}