Cod sursa(job #1378414)

Utilizator RathebaSerbanescu Andrei Victor Ratheba Data 6 martie 2015 12:03:35
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;
#define MAX 50005
#define INF 50000000

struct pereche
{
    int nod, cost;
};

vector<pereche> v[MAX];
queue<int> q;
int drum[MAX], fv[MAX], n, m;
bool ok;

void bm(int sursa);

int main()
{
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);
    int i, a, b, c;
    pereche p;
    scanf("%d%d", &n, &m);
    for(i=1; i<=m; i++)
    {
        scanf("%d%d%d", &a, &b, &c);
        p.nod = b; p.cost = c;
        v[a].push_back(p);
    }
    for(i=1; i<=n; i++)
        drum[i] = INF;
    bm(1);
    if(!ok)
        printf("Ciclu negativ!");
    else
        for(i=2; i<=n; i++)
            printf("%d ", drum[i]);

    return 0;
}
void bm(int sursa)
{
    int tata, fiu, cost;
    vector<pereche>::iterator it;
    drum[sursa] = 0;
    q.push(sursa);
    while(!q.empty())
    {
        tata = q.front();
        q.pop();
        fv[tata]++;
        if(fv[tata] > n){ok = 0; return;}
        for(it=v[tata].begin(); it!=v[tata].end(); ++it)
        {
            fiu = it -> nod;
            cost = it -> cost;
            if(drum[fiu] > drum[tata] + cost)
            {
                q.push(fiu);
                drum[fiu] = drum[tata] + cost;
            }
        }
    }
    ok = 1;
}