Cod sursa(job #2274260)

Utilizator alexge50alexX AleX alexge50 Data 1 noiembrie 2018 16:33:20
Problema Distante Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.35 kb
#include <list>
#include <queue>
#include <vector>
#include <fstream>
#include <limits>
#include <memory>

const int INF = INT32_MAX - 1;

struct Edge
{
    int from, to;
    int cost;
};

std::unique_ptr<std::vector<int>> dijkstra(const std::vector<std::vector<Edge>> &graph, int nNodes, int startNode)
{
    std::unique_ptr<std::vector<int>> result{ new std::vector<int>{} };
    std::vector<int> &distances = *result;
    std::vector<bool> was;
    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> pq;

    distances.insert(distances.begin(), static_cast<unsigned long>(nNodes), INF);
    was.insert(was.begin(), static_cast<unsigned long>(nNodes), false);

    distances[startNode] = 0;
    pq.push({distances[startNode], startNode});
    while(!pq.empty())
    {
        while(!pq.empty() && was[pq.top().second])
            pq.pop();

        if(!pq.empty())
        {
            int x = pq.top().second;
            pq.pop();

            for(auto edge: graph[x])
            {
                if(distances[x] + edge.cost < distances[edge.to])
                {
                    distances[edge.to] = distances[x] + edge.cost;
                    pq.push({distances[edge.to], edge.to});
                }
            }
        }
    }

    return result;
}

int main()
{
    std::ifstream fin("distante.in");
    std::ofstream fout("distante.out");
    int t{};

    fin >> t;
    while((t --) > 0)
    {
        int nNodes, nEdges, startNode;
        std::vector<std::vector<Edge>> edges;
        std::vector<int> d;


        fin >> nNodes >> nEdges >> startNode;

        d.insert(d.begin(), static_cast<unsigned long>(nNodes), {});
        for(int i = 0; i < nNodes; i++)
            fin >> d[i];

        edges.insert(edges.begin(), static_cast<unsigned long>(nNodes), {});
        for(int i = 0; i < nEdges; i++)
        {
            Edge e{};
            fin >> e.from >> e.to >> e.cost;

            e.from --;
            e.to --;
            edges[e.from].push_back(e);
            edges[e.to].push_back({e.to, e.from, e.cost});
        }

        auto d2 = dijkstra(edges, nNodes, startNode - 1);
        bool ok = true;

        for(int i = 0; i < nNodes; i++)
            ok = ok && ((*d2)[i] == d[i]);

        const char* boolToString[2] = {"NU", "DA"};

        fout << boolToString[ok] << '\n';
    }

    return 0;
}