Cod sursa(job #807374)

Utilizator romircea2010FMI Trifan Mircea Mihai romircea2010 Data 4 noiembrie 2012 17:40:28
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.21 kb
#include <fstream>
#include <vector>
#include <set>
#define INF 2000000000

using namespace std;

int n, m;
struct NOD
{
    int x, cost;
};
vector <NOD> a[50005];
set<pair<int, int> > S;
int d[50005];
bool v[50005];

inline void Read()
{
    ifstream f("dijkstra.in");
    f>>n>>m;
    int i, x, y, cost;
    NOD aux;
    for(i=1; i<=m; i++)
    {
        f>>x>>y>>cost;
        aux.x = y;
        aux.cost = cost;
        a[x].push_back(aux);
    }
    f.close();
}

inline void Dijkstra()
{
    int i;
    for(i=1; i<=n; i++)
    {
        d[i] = INF;
    }
    d[1] = 0;

    int minim, x, y, cost, k;
    bool stop = false;

    pair <int, int> pereche;
    pereche.first = 0;
    pereche.second = 1;

    S.insert(pereche);

    set<pair<int, int> >::iterator itp;

    vector <NOD>::iterator it, final;
    NOD aux;

    for (int pas = 1; pas<n && !stop; pas++)
    {
        itp = S.begin();
        pereche = *itp;
        k = pereche.second;

        if (S.empty())
        {
            stop = true;
        }
        else
        {
            S.erase(pereche);

            v[k] = true;
            it = a[k].begin();
            final = a[k].end();
            for(; it!=final; it++)
            {
                // parcurg toti adiacentii lui k, pentru care am gasit distanta minima, si ii actualizez si pe ei
                aux = *it;
                x = aux.x;
                cost = aux.cost;
                if (d[x] > d[k] + cost)
                {
                    pereche.first = d[x];
                    pereche.second = x;
                    S.erase(S.find(pereche));
                    d[x] = d[k] + cost;
                    pereche.first = d[x];
                    pereche.second = x;
                    S.insert(pereche);
                }
            }
        }
    }
}

inline void Write()
{
    int i;
    ofstream g("dijkstra.out");
    for(i = 2; i<=n; i++)
    {
        if (d[i] < INF)
        {
            g<<d[i]<<" ";
        }
        else
        {
            g<<"0 ";
        }
    }
    g<<"\n";
    g.close();
}

int main()
{
    Read();
    Dijkstra();
    Write();
    return 0;
}