Cod sursa(job #1311697)

Utilizator blue_skyPetrica Stefan Cosmin blue_sky Data 8 ianuarie 2015 15:18:06
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <list>
#include <queue>
#define DIM 50001
#define INF 99999999

using namespace std;
int n,m,x,y;
long long d[DIM];

struct point
{
    int x,cost;
    bool operator <(const point &other) const
    {
        return d[x]>d[other.x];
    }
};

list<point> nod[DIM];
priority_queue<point> cd;

void dijkstra(int k)
{
    for(int i=1;i<=n;++i)
    d[i]=INF;
    d[k]=0;
    point q,vf;
    q.x=k;
    cd.push(q);
    while(!cd.empty())
    {
        vf=cd.top();
        for(list<point>::iterator i=nod[vf.x].begin();i!=nod[vf.x].end();++i)
        {
            point aux=*i;
            if(d[vf.x]+aux.cost<d[aux.x])
            {
                d[aux.x]=d[vf.x]+aux.cost;
                q.x=aux.x;
                cd.push(q);
            }
        }
        cd.pop();
    }
}

int main()
{
    ifstream f("dijkstra.in");
    ofstream g("dijkstra.out");
    f>>n>>m;
    for(int i=1;i<=m;++i)
    {
        f>>x>>y;
        point q;
        f>>q.cost;
        q.x=y;
        nod[x].push_back(q);
        q.x=x;
        nod[y].push_back(q);
    }

    dijkstra(1);
    for(int i=2;i<=n;++i)
    {
        if(d[i]==INF) g<<"0 ";
        else g<<d[i]<<" ";
    }
    g<<'\n';
    f.close();
    g.close();
    return 0;
}