Cod sursa(job #1792450)

Utilizator Emil64Emil Centiu Emil64 Data 30 octombrie 2016 14:39:18
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

#define infinit 2000000

using namespace std;

struct _arc
{
    int cost, destinatie;
} arc;
struct nod
{
    vector<_arc> v;
} v[50001];

bool cmp(_arc a1, _arc a2)
{
    return (a1.cost>a2.cost);
}

vector<_arc> h;
bool viz[50001];
int sol[50001];

int main()
{
    ifstream f("dijkstra.in");
    ofstream g("dijkstra.out");

    int i, j, n, m, a, b, c;
    f>>n>>m;
    for(i=1; i<=n; i++)
        sol[i] = infinit;
    for(i=1; i<=m; i++)
    {

        f>>a>>b>>c;
        arc.destinatie = b;
        arc.cost = c;
        v[a].v.push_back(arc);
    }

    for(i=1; i<=n; i++)
        sol[i] = infinit;
    sol[1] = 0;
    for(i=0; i< v[1].v.size(); i++)
    {
        h.push_back(v[1].v[i]);
        sol[v[1].v[i].destinatie] = v[1].v[i].cost;
    }
    make_heap(h.begin(), h.end(), cmp);
    viz[1] = true;

    while(!h.empty())
    {

        arc = h.front();
        pop_heap(h.begin(), h.end(), cmp);
        h.pop_back();
        if(arc.cost <= sol[arc.destinatie])
            sol[arc.destinatie] = arc.cost;
        viz[arc.destinatie] = true;
        for(i=0; i< v[arc.destinatie].v.size(); i++)
        {

            if(!viz[v[arc.destinatie].v[i].destinatie])
            {
                v[arc.destinatie].v[i].cost += arc.cost;
                h.push_back(v[arc.destinatie].v[i]);
                push_heap(h.begin(), h.end(), cmp);
            }
        }
    }

    for(i=2; i<=n; i++)
        if(sol[i] == infinit)
            g<<"0 ";
        else g<<sol[i]<<" ";
}