Cod sursa(job #2836372)

Utilizator mihneadv@yahoo.comDavid Mihnea Stefan [email protected] Data 20 ianuarie 2022 11:22:35
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include<fstream>
#include<vector>
#include<queue>
#include<limits.h>

using namespace std;

vector<vector<pair<int,int>>>v;
priority_queue<pair<int,int>>q;
vector<int>cost;

ifstream cin("dijkstra.in");
ofstream cout("dijkstra.out");

void solve()
{
    while(!q.empty())
    {
        pair<int,int> x = q.top();
        q.pop();
        for(auto& it : v[x.second])
        {
            if(cost[it.first] < x.first + it.second)
            {
                cost[it.first] = x.first + it.second;
                q.push({cost[it.first], it.first});
            }
        }
    }
}

int main()
{
    int n, p;
    cin >> n >> p;
    p--;
    cost.resize(n, INT_MIN);
    v.resize(n);
    int V1, V2, C;
    while(cin >> V1 >> V2 >> C)
    {
        V1--, V2--;
        v[V1].push_back({V2, -C});
    }
    cost[p] = 0;
    q.push({0, p});
    solve();
    for(int i = 0; i < n; i ++)
    {
        if(cost[i] == INT_MIN)
        {
            cout << -1 << " ";
        }
        else
        cout << -cost[i] << " ";
    }
    return false;
}