Cod sursa(job #3275874)

Utilizator BledeaAlexBledea Alexandru BledeaAlex Data 11 februarie 2025 20:51:27
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
#include <bits/stdc++.h>

using namespace std;

const int N_MAX = 36005, INF = 1e9;
int N, M, K;
int F[N_MAX];
int dist[N_MAX];
vector<int> fortarete;

struct Edge
{
    int v;
    int d;

    Edge(int _v, int _d) :
        v(_v), d(_d) {}

    Edge() {}

    inline bool operator> (const Edge& rhs) const
    {
        return d > rhs.d;
    }
};

vector<Edge> G[N_MAX];

void SetInput(string name)
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    (void)!freopen((name + ".in").c_str(), "r", stdin);
    (void)!freopen((name + ".out").c_str(), "w", stdout);
}

void ReadInput()
{
    cin >> N >> M >> K;
    for(int i = 0, v; i < K; i++)
    {
        cin >> v;
        fortarete.push_back(v);
    }
    for(int i = 0, v1, v2, d; i < M; i++)
    {
        cin >> v1 >> v2 >> d;
        G[v1].emplace_back(v2, d);
        G[v2].emplace_back(v1, d);
    }
}

void Dijkstra(vector<int>& fortarete)
{
    priority_queue<Edge, vector<Edge>, greater<Edge>> PQ;

    for(int i = 1; i <= N; i++)
        dist[i] = INF;

    for(int& fort : fortarete)
    {
        dist[fort] = 0;
        PQ.emplace(fort, 0);
        F[fort] = fort;
    }

    while(not PQ.empty())
    {
        auto [v, d] = PQ.top();
        PQ.pop();

        if(d > dist[v])
            continue;

        for(auto& [fiu, cost] : G[v])
            if(dist[fiu] > d + cost)
            {
                dist[fiu] = d + cost;
                F[fiu] = F[v];
                PQ.emplace(fiu, dist[fiu]);
            }
            else if(dist[fiu] == d + cost)
                F[fiu] = min(F[fiu], F[v]);
    }
}

void Solve()
{
    Dijkstra(fortarete);

    for(int& fort : fortarete)
        F[fort] = 0;

    for(int i = 1; i <= N; i++)
        cout << F[i] << ' ';
}

int main()
{
    SetInput("catun");

    ReadInput();
    Solve();

    return 0;
}