Cod sursa(job #2540532)

Utilizator bogdan2604Bogdan Dumitrescu bogdan2604 Data 7 februarie 2020 12:17:51
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <bits/stdc++.h>
#define N 50001
#define inf 0x3f3f3f3f

using namespace std;

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

auto cmp = [] (pair<int,int> a, pair<int,int> b)
{
    return a.second > b.second;
};
priority_queue <pair<int,int>, vector<pair<int,int>>, decltype(cmp)> pq(cmp);

int n,m,i,x,y,a,b,pret,cost[N];
vector <vector<pair<int,int>>> v;
bitset <N> trecut;

int main()
{
    ios::sync_with_stdio(0);
    f >> n >> m;
    v.resize(n + 1);
    while(m --)
    {
        f >> x >> y >> pret;
        v[x].push_back({y,pret});
        v[y].push_back({x,pret});
    }
    for(i = 1; i <= n; ++ i)
        cost[i] = inf;
    for(i = 0; i < v[1].size(); ++ i)
    {
        a = v[1][i].first;
        b = v[1][i].second;
        cost[a] = b;
        pq.push({a,b});
    }
    cost[1] = 0;
    trecut[1] = 1;
    while(!pq.empty())
    {
        a = pq.top().first;
        b = pq.top().second;
        pq.pop();
        if(trecut[a])
            continue;
        trecut[a] = 1;
        for(i = 0; i < v[a].size(); ++ i)
        {
            x = v[a][i].first;
            y = v[a][i].second;
            if(!trecut[x] && cost[x] > b + y)
            {
                cost[x] = b + y;
                pq.push({x, b + y});
            }
        }
    }
    for(i = 2; i <= n; ++ i)
        if(trecut[i])
            g << cost[i] << ' ';
        else
            g << 0 << ' ';
}