Cod sursa(job #2602154)

Utilizator paul3ioanCirstean Paul Ioan paul3ioan Data 16 aprilie 2020 01:18:04
Problema Algoritmul lui Dijkstra Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <fstream>
#include <vector>
#include <set>
using namespace std;
ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");
const int N = 500001, Inf =1e9;
int n ,m ;
set <pair<int, pair<int,int>> >s;
int cost[N],viz[N], can[N];
int x , y ,z ;
vector <pair<int,int> > L[N];
void read();
void dfs(int x)
{
    can[x] = 1;
    for(auto i : L[x])
        if(!can[i.first])
            dfs(i.first);
}
void init();
void dijkstra();
void push(int x)
{
    for(auto i : L[x])
    {
        if(cost[x] + i.second < cost[i.first])
            cost[i.first] = cost[x] + i.second;
        s.insert({i.second, {x, i.first}});
    }
}
void write();
int main() {

    read();
    init();
    dijkstra();
    write();
    return 0;
}
void read()
{
    cin >> n >> m;
    for(int i =1 ;i <=m ;i ++)
    {
        cin >> x >> y >> z;
        L[x].push_back({y,z});
//        L[y].push_back({x,z});
    }
}
void init()
{
    for(int i = 1 ;i <=n; i ++)
        cost[i] = Inf;
    cost[1] = 0;
    viz[1] = 1;
    push(1);
    dfs(1);
}
void dijkstra()
{
    for(int i = 2 ;i <=n; i ++)
    {
        if(can[i]) {
            auto nod = s.begin();
            while (true) {
//                if (s.empty())
//                    break;
                nod = s.begin();
                if (viz[nod->second.second])
                    s.erase(nod);
                else {
                    break;
                }
            }
            viz[nod->second.second] = 1;
            push(nod->second.second);
        }
    }
}
void write()
{
    for(int i =2 ;i <=n; i ++)
        if(cost[i] == Inf)
            cout << 0 << " ";
        else
        cout << cost[i]<<" ";
}