Cod sursa(job #1139354)

Utilizator UAIC_Balan_Negrus_HreapcaUAIC Balan Negrus Hreapca UAIC_Balan_Negrus_Hreapca Data 11 martie 2014 00:46:30
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iterator>
#include <random>
#include <assert.h>
using namespace std;

const string file = "bellmanford";

const string infile = file + ".in";
const string outfile = file + ".out";

const int INF = 0x3f3f3f3f; 

//#define ONLINE_JUDGE

int main()
{
#ifdef ONLINE_JUDGE
	ostream &fout = cout;
	istream &fin = cin;
#else
	fstream fin(infile.c_str(), ios::in);
	fstream fout(outfile.c_str(), ios::out);
#endif	

    int N, M;
    fin >> N >> M;
    vector<vector<pair<int, int> > > G(N + 1);
    for(int i = 0; i < M; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        G[x].push_back(make_pair(y, c));
    }
    queue<int> que;
    vector<int> updated(N + 1, 0);
    vector<bool> inQ(N + 1, false);
    vector<int> dist(N + 1, INF);
    
    que.push(1);
    inQ[1] = true;
    updated[1] = 0;
    dist[1] = 0;

    while(que.empty() == false)
    {
        int x = que.front();
        inQ[x] = false;
        que.pop();
        for(vector<pair<int, int> >::iterator itr = G[x].begin();
                itr != G[x].end();
                itr++)
        {
            int dst = itr->first;
            int cst = itr->second;
            if(dist[dst] > dist[x] + cst)
            {
                dist[dst] = dist[x] + cst;
                updated[dst] ++;
                if(updated[dst] == N)
                {
                    fout << "Ciclu negativ!\n";
                    return 0;
                }
                if(inQ[dst] == false)
                {
                    inQ[dst] = true;
                    que.push(dst);
                }
            }
        }
    }
    for(int i = 2; i <= N; i++)
    {
        fout << dist[i] << " ";
    }
    fout << "\n";

#ifdef ONLINE_JUDGE
#else
    fout.close();
	fin.close();
#endif
}