Cod sursa(job #898540)

Utilizator vgabi94Vaduva Gabriel vgabi94 Data 28 februarie 2013 10:37:53
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

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

const int maxn = 50001;
const int maxm = 250001;
const int inf = 0x7ffffff;
int N, M, dist[maxn], count[maxn];
struct edge {
    edge(int u, int v, int c) { this->u = u; this->v = v; this->c = c; }
    int u, v, c;
};
vector<edge> E;
vector<int> v[maxn];  // muchia i incidenta cu nodul E[i].u
queue<int> qu;        // coada nodurilor
bitset<maxn> in_qu;

int main()
{
    int p, q, w; E.reserve(maxm); bool negative = false;
    in >> N >> M;
    for (int i = 0; i < M; i++)
    {
        in >> p >> q >> w;
        E.push_back(edge(p, q, w));
        v[ E[i].u ].push_back(i);
    }
    for (int i = 2; i <= N; i++) dist[i] = inf; // 1 e nodul sursa | dist[1] == 0
    qu.push(1);
    while(!qu.empty() && !negative)
    {
        int front = qu.front(); qu.pop();
        in_qu[front] = false;
        for (int i = 0; i < v[front].size(); i++)
        {
            int pos = v[front][i];
            if ( dist[ E[pos].u ] + E[pos].c < dist[ E[pos].v ] )
            {
                dist[ E[pos].v ] = dist[ E[pos].u ] + E[pos].c;
                if (!in_qu[ E[pos].v ])
                {
                    if (count[ E[pos].v ] > N) {
                        negative = true; continue;
                    }
                    else {
                        qu.push(E[pos].v);
                        in_qu[ E[pos].v ] = true;
                        count[ E[pos].v ]++;
                    }
                }

            }
        }
    }
    if (!negative) {
        for (int i = 2; i <= N; i++)
            out << dist[i] << ' ';
    }

    return 0;
}