Cod sursa(job #2505912)

Utilizator Vladv01Vlad Vladut Vladv01 Data 7 decembrie 2019 11:45:24
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <set>

using namespace std;


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

struct node{

int y,cost;
bool operator<(const node& other) const
        {
            if(cost !=other.cost)
                return cost<other.cost;
            return y<other.y;
        }

};

set<node> q;

vector <node> a[50005];
int d[50005],viz[50005];
int inf=0x3f3f3f3f;
int x,y,c,n,m;




void cit()
{
    f>>n>>m;
    for(int i=1;i<=m;i++)
    {
        f>>x>>y>>c;
        a[x].push_back({y,c});
    }
}

void rezolv()
{
    while(!q.empty())
    {
        int nod=q.begin()->y;
        q.erase(q.begin());
        for(const auto& i:a[nod])
        {
            if (d[i.y] > d[nod] + i.cost) {
                if (d[i.y] != inf)
                    q.erase({i.y, d[i.y]});
                d[i.y] = d[nod] + i.cost;
                q.insert({i.y, d[i.y]});

        }
    }

}
}


void afis() {
    for (int i = 2; i <= n; ++i)
        if(d[i]==inf)
            g<<0<<" ";
        else
            g<<d[i]<<" ";
}

int main()
{
    cit();
    for(int i=2;i<=n;i++)
        d[i]=inf;
    q.insert({1,0});
    rezolv();
    afis();
    return 0;
}