Cod sursa(job #2072999)

Utilizator BogdanNeghinaNeghina Bogdan BogdanNeghina Data 22 noiembrie 2017 16:42:15
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <vector>
#include <queue>
#define infinit (1<<30)
using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
int n,m,d[50005];
bool einheap[50005];
struct nod
{
    int x,c;
};
vector <nod> v[50005];
class cmp
{
   public: bool operator() (int a, int b)
    {
        if(d[a]>d[b])
            return 1;
        return 0;
    }
};
priority_queue <int,vector <int>,cmp> heap;
void dijkstra (int x)
{
    heap.push(x);
    einheap[x]=1;
    while(heap.size())
    {
        x=heap.top();
        heap.pop();
        einheap[x]=0;
        for(int i=0;i<v[x].size();i++)
        {
            int y=v[x][i].x;
            if(d[y]>d[x]+v[x][i].c)
            {
                d[y]=d[x]+v[x][i].c;
                if(!einheap[y])
                {
                    heap.push(y);
                    einheap[y]=1;
                }
            }
        }
    }
}
void afisare()
{
    for(int i=2;i<=n;i++)
        if(d[i]==infinit)
            cout<<0<<" ";
        else
            cout<<d[i]<<" ";
}
int main ()
{
    cin>>n>>m;
    int x,y,c;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y>>c;
        v[x].push_back({y,c});
    }
    for(int i=1;i<=n;i++)
        d[i]=infinit;
    d[1]=0;
    dijkstra(1);
    afisare();
    return 0;
}