Cod sursa(job #443797)

Utilizator AstronothingIulia Comsa Astronothing Data 18 aprilie 2010 14:23:06
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

vector<pair<int,int> > G[50001];
int N,M;
const int INF = 5000;

ofstream f2("bellmanford.out");

bool bellmanford()
{
    bool viz[50001];
    memset(viz,0,sizeof(viz));
    int cnt[50001];
    memset(cnt,0,sizeof(cnt));
    int dist[50001];
    for(int i=0; i<N; ++i) dist[i] = INF;
    queue<int> q;
    dist[0] = 0;
    viz[0] = 1;
    cnt[0] = 1;
    q.push(0);
    while(!q.empty())
    {
        int crt = q.front();
        q.pop();
        for(int i=0; i<G[crt].size(); ++i)
        {
            int vecin = G[crt][i].first;
            int cost = G[crt][i].second;
            if(dist[vecin]>cost+dist[crt])
            {
                dist[vecin] = cost+dist[crt];
                ++cnt[vecin];
                if(cnt[vecin]>=N) return 0;
                if(!viz[vecin])
                {
                    q.push(vecin);
                    viz[vecin] = 1;
                }
            }
        }
        viz[crt] = 0;
    }
    for(int i=1; i<N; ++i) f2<<dist[i]<<" ";
    return true;
}

int main()
{
    ifstream f("bellmanford.in");

    f>>N>>M;
    int x,y,c;
    while(f>>x>>y>>c)
    {
        --x; --y;
        G[x].push_back(make_pair(y,c));
    }
    if(!bellmanford()) f2<<"Ciclu negativ!";
    return 0;
}