Cod sursa(job #2196167)

Utilizator PredaBossPreda Andrei PredaBoss Data 18 aprilie 2018 17:47:31
Problema Algoritmul Bellman-Ford Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>
#define INF 1e9
using namespace std;
struct muchie
{
    int first,second,lenght;
};
vector<muchie>muc;
vector<int>inc[50005];
deque<int>verify;
int last[50005];
int mn[50005];
int n,m,pos1,pos2,l;
int main()
{
    freopen("bellmanford.in","r",stdin);
    freopen("bellmanford.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&pos1,&pos2,&l);
        muc.push_back({pos1,pos2,l});
        verify.push_back(i-1);
        inc[pos1].push_back(i-1);
    }
    for(int i=2;i<=n;i++)
        mn[i]=INF;
    mn[1]=0;
    int i;
    for(i=1;i<=n-1;i++)
    {
        bool k=0;
        int howfar=verify.size();
        for(int j=0;j<howfar;j++)
        {
            int pos=verify.front();
            verify.pop_front();
            if(mn[muc[pos].second]<=mn[muc[pos].first]+muc[pos].lenght)
                continue;
            k=1;
            mn[muc[pos].second]=mn[muc[pos].first]+muc[pos].lenght;
            if(last[muc[pos].second]==i)
                continue;
            last[muc[pos].second]=i;
            for(int g=0;g<inc[muc[pos].second].size();g++)
            verify.push_back(inc[muc[pos].second][g]);
        }
        if(k==0)
            break;
    }
    bool k=0;
    if(i==n)
    {
        for(int j=0;j<m;j++)
        {
            if(mn[muc[j].second]<=mn[muc[j].first]+muc[j].lenght)
                continue;
            k=1;
            mn[muc[j].second]=mn[muc[j].first]+muc[j].lenght;
        }
        if(k==1)
        {
            printf("Ciclu negativ!");
            return 0;
        }
    }
    for(int i=2;i<=n;i++)
        printf("%d ",mn[i]);
    return 0;
}