Cod sursa(job #1330490)

Utilizator sorynsooSorin Soo sorynsoo Data 30 ianuarie 2015 18:30:36
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>
#include <queue>
using namespace std;

struct nod
{
    int val, cost;
};
vector <nod> grf[50001];
queue <int> coada;
int d[50001];
bool ok;
int ccost[50001];
bool incoada[50001];
int main()
{
    int n, m, i, a, b, c;
    ifstream f("dijkstra.in");
    ofstream g("dijkstra.out");
    f>>n>>m;
    for(i=1; i<=m; i++)
    {
        f>>a>>b>>c;
        nod act;
        act.val=b;
        act.cost=c;
        grf[a].push_back(act);
    }
    for(i=1; i<=n; i++)
    {
        d[i]=10000000;
    }
    coada.push(1);
    d[1]=0;
    incoada[1]=1;
    while(!coada.empty() && !ok)
    {
        int cx=coada.front();
        coada.pop();
        incoada[cx]=0;
        for(i=0; i<grf[cx].size(); i++)
        {
            if(d[cx]+grf[cx][i].cost<d[grf[cx][i].val])
            {
                d[grf[cx][i].val]=d[cx]+grf[cx][i].cost;
                if(!incoada[grf[cx][i].val])
                {
                    if(ccost[grf[cx][i].val]>n)
                        ok=true;
                    else
                    {
                        coada.push(grf[cx][i].val);
                        ccost[grf[cx][i].val]++;
                        incoada[grf[cx][i].val]=1;
                    }
                }

            }
        }
    }
    if(ok)
    {
        g<<"Ciclu negativ!";
    }
    else
    {
    for(i=2; i<=n; i++)
    {
        if(d[i]!=10000000)
            g<<d[i]<<" ";
        else
            g<<0<<" ";
    }
    }
}