Cod sursa(job #1825777)

Utilizator tudormaximTudor Maxim tudormaxim Data 9 decembrie 2016 17:17:55
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

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

const int maxn = 5e4 + 5;
const int oo = 1 << 29;
vector < pair <int,int> > G[maxn];
int Dist[maxn], n, Cnt[maxn];

bool BellmanFord(int source) {
    queue <int> Q;
    bitset <maxn> Vis = 0;
    vector <pair <int,int> > :: iterator it;
    int node, i;
    for (i = 1; i <= n; i++) {
        Dist[i] = oo;
    }
    Dist[source] = 0;
    Q.push(source);
    while (!Q.empty()) {
        node = Q.front();
        Vis[node] = false;
        Q.pop();
        for (it = G[node].begin(); it != G[node].end(); it++) {
            if (Dist[it->first] > Dist[node] + it->second) {
                Dist[it->first] = Dist[node] + it->second;
                if (Vis[it->first] == false) {
                    Vis[it->first] = true;
                    Cnt[it->first]++;
                    Q.push(it->first);
                    if (Cnt[it->first] > n) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

int main() {
    ios_base :: sync_with_stdio (false);
    int m, x, y, c, i;
    fin >> n >> m;
    for (i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        G[x].push_back(make_pair(y, c));
    }
    bool Cycle = BellmanFord(1);
    if (Cycle == true) {
        fout << "Ciclu negativ!";
    } else {
        for (i = 2; i <= n; i++) {
            if (Dist[i] != oo) {
                fout << Dist[i] << " ";
            } else {
                fout << "0 ";
            }
        }
    }
    fin.close();
    fout.close();
    return 0;
}