Cod sursa(job #1493503)

Utilizator gabi.cristacheGabi Cristache gabi.cristache Data 29 septembrie 2015 15:20:14
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#include <utility>
#include <algorithm>

#define MaxN 50005
#define Inf 123456789

using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

int N, M, x, y, c;
vector<pair<int, int> > G[MaxN];

int main()
{
    fin >> N >> M;

    for (int i = 1; i <= M; ++i) {
        fin >> x >> y >> c;
        G[x].push_back(make_pair(y, c));
    }

    queue<int> q;
    bitset<MaxN> inQueue(false);
    vector<int> dist(N + 1, Inf), countInQueue(N + 1, 0);
    bool negativeCycle = false;

    dist[1] = 0;
    q.push(1);

    while (!q.empty() && !negativeCycle) {
        int node = q.front();
        q.pop();

        inQueue[node] = false;

        vector<pair<int, int> >::iterator it;

        for (it = G[node].begin(); it != G[node].end(); ++it) {
            if (dist[node] + it->second < dist[it->first]) {
                dist[it->first] = dist[node] + it->second;

                if (!inQueue[it->first]) {
                    if (countInQueue[it->first] > N) {
                        negativeCycle = true;
                    } else {
                        q.push(it->first);
                        inQueue[it->first] = true;
                        countInQueue[it->first]++;
                    }
                }
            }
        }
    }

    if (negativeCycle) {
        fout << "Ciclu negativ!\n";
    } else {
        for (int i = 2; i <= N; ++i)
            if (dist[i] != Inf)
                fout << dist[i] << ' ';
            else
                fout << "0 ";
        fout << '\n';
    }


    return 0;
}