Cod sursa(job #2696865)

Utilizator dariahazaparuHazaparu Daria dariahazaparu Data 16 ianuarie 2021 23:56:56
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.52 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

const int N_MAX = 1000005;
const int INF = 1e9;

std :: vector <std :: pair <int, int> > graph[N_MAX];
std :: queue <int> q;
int dist[N_MAX], cicle[N_MAX];
bool vis[N_MAX];
int n, m;

int main()
{
    std :: ifstream fin("bellamnford.in");
    std :: ofstream fout("bellmanford.out");
    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {   int a, b, cost;
        fin >> a >> b >> cost;
        graph[a].emplace_back(b, cost);
    }
    for (int i = 1; i <= n; ++i) {
        dist[i] = INF;
    }

    dist[1] = 0;
    vis[1] = true;
    q.push(1);
    while (q.empty() != 1)
    {
        int node = q.front();
        for (int i = 0; i <graph[node].size(); ++i)
        {
            int next = graph[node][i].first;
            int cost = graph[node][i].second;
            if (dist[node] + cost < dist[next])
            {
                dist[next]=dist[node] + cost;
                if (vis[next] == 0)
                {
                    vis[next]=1;
                    q.push(next);
                    cicle[next]++;
                    if (cicle[next] >= n)
                    {
                        fout << "Ciclu negativ!";
                        return 0;
                    }
                }
            }
        }
        vis[node] = false;
        q.pop();
    }
    for (int i = 2; i <= n; ++i) fout << dist[i] << " ";

    return 0;
}


//

//
//int main() {

//
//    fin >> n >> m;
//    for (int i = 1; i <= m; i++) {
//        int a, b, c;
//        fin >> a >> b >> c;
//        graph[a].emplace_back(b, c);
//    }
//
//    for (int i = 1; i <= n; ++i) {
//        dist[i] = INF;
//    }
//
//    dist[1] = 0;
//    vis[1] = true;
//    q.push(1);
//    while (q.empty() != 1) {
//
//        int node = q.front();
//        for (auto i : graph[node]) {
//            int nenodet = i.first;
//            int cost = i.second;
//            if (dist[node] + cost < dist[nenodet]) {
//                dist[nenodet] = dist[node] + cost;
//                if (!vis[nenodet]) {
//                    vis[nenodet] = true;
//                    q.push(nenodet);
//                    cicle[nenodet]++;
//                    if (cicle[nenodet] >= n) {
//                        fout << "Ciclu negativ!";
//                        return 0;
//                    }
//                }
//            }
//        }
//        q.pop();
//        vis[node] = false;
//    }
//
//
//    for (int i = 2; i <= n; ++i) {
//        fout << dist[i] << " ";
//    }
//
//    return 0;
//}