Cod sursa(job #3235114)

Utilizator AlexandruTigauTigau Alexandru AlexandruTigau Data 14 iunie 2024 17:18:34
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
#define INF 50000
struct muchie{
    long long end,cost;
};
vector <muchie> v[INF+1];
vector <long long> times[INF+1];
queue <long long> q;
long long dist[INF+1];
int main()
{
    int n,m;
    f>>n>>m;
    for(int i=1;i<=n;i++)
        dist[i]=INF*1000;
    for(int i=1;i<=m;i++)
    {
        int x,y,c;
        f>>x>>y>>c;
        v[x].push_back({y,c});
        times[x].push_back(0);
    }
    q.push(1); dist[1]=1;
    int ok=1;
    while(!q.empty()&&ok)
    {
        int x=q.front();
        int l=v[x].size();
        for(int i=0;i<l&&ok;i++)
        {
            int y=v[x][i].end,z=v[x][i].cost;
            if(dist[y]>dist[x]+z)
            {
                dist[y]=dist[x]+z;
                q.push(y);
                times[x][i]++;
                if(times[x][i]==n)
                    ok=0;
            }
        }
        q.pop();
    }
    if(!ok)
        g<<"Ciclu negativ!";
    else for(int i=2;i<=n;i++)
            g<<dist[i]-1<<" ";
    return 0;
}