Cod sursa(job #1339951)

Utilizator roxana_97Soare Roxana Florentina roxana_97 Data 11 februarie 2015 13:05:42
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
// Dijkstra - O(MlogN)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#define Nmax 50009
#define oo 2000000000
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

int N,M,S,F,d[Nmax],x,y,ante[Nmax];
bitset < Nmax > inPQ;
struct muchie
{
    int nod,c;
}aux;
vector < muchie > Graph[Nmax];

struct cmp
{
    bool operator()(int x, int y)
    {
        if(d[x] > d[y]) return 1;
        return 0;
    }
};
priority_queue < int  , vector < int > , cmp > pq;


void Dijkstra(int S)
{
    for(int i=1;i<=N;++i)d[i]=oo,ante[i]=oo;
    d[S]=ante[S]=0;
    pq.push(S);
    while(!pq.empty())
    {
        int node=pq.top();
        pq.pop();
        inPQ[node]=0;
        for(vector<muchie>::iterator it=Graph[node].begin() ; it!=Graph[node].end() ; ++it)
            if(d[node]+it->c < d[it->nod])
            {
                d[it->nod]=d[node]+it->c;
                ante[it->nod]=node;
                if(inPQ[it->nod]==0) {
                    pq.push(it->nod);
                    inPQ[it->nod]=1;
                }
            }
    }
    for (int i=1; i<=N; ++i)
        if (d[i]==oo)d[i]=0,ante[i]=0;
}


void Rebuild(int node)
{
    if(node==S){ g<<S<<' '; return; }
    Rebuild(ante[node]);
    g<<node<<' ';
}



int main()
{
    f>>N>>M; S=1; F=N;
    for(int i=1;i<=M;++i)

        {
            f>>x>>aux.nod>>aux.c;
            Graph[x].push_back(aux);
            /*
                f>>x>>y>>c;
                aux.nod=y; aux.c=c;
                Graph[x].push_back(aux);
                aux.nod=x; aux.c=c;
                Graph[y].push_back(aux);
            */
        }
    Dijkstra(S);
    for(int i=2; i<=N; i++)g<<d[i]<< ' ';
    g<<'\n';
    f.close();g.close();

    return 0;
    g<<"Drumul de la "<<S<< " la "<<F<<" are lungimea "<<d[F]<<"\n";    	g<<"si este:\n";
    Rebuild(F);
    g<<'\n';
    f.close();g.close();
    return 0;
}