Cod sursa(job #1547780)

Utilizator BaweeLazar Vlad Bawee Data 9 decembrie 2015 21:35:08
Problema Arbore partial de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include <fstream>
#include <vector>
#include <utility>
#include <algorithm>
#include <cstring>

using namespace std;

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

const int MaxN = 50001;
const int INF = 1 << 30;
vector < pair < int,int> > G[MaxN];
vector <int> heap;

int n,m,t,source;
int checkDist[MaxN],d[MaxN];

bool cmp(const int& a, const int& b)
{
    return d[a] > d[b];
}

void dijkstra(int source)
{
    for(int i = 1; i <= n; ++i) d[i] = INF;
    d[source] = 0;

    heap.push_back(source);
    make_heap(heap.begin(),heap.end(), cmp);

    while(heap.size())
    {
        int node = heap.front();
        pop_heap(heap.begin(),heap.end(), cmp);
        heap.pop_back();

        for(vector < pair <int,int> >::iterator it = G[node].begin(); it != G[node].end(); ++it)
        {
            int newNode = it -> first;
            int newNodeDist = it -> second;

            if(d[newNode] > d[node] + newNodeDist)
            {
                d[newNode] = d[node] + newNodeDist;
                heap.push_back(newNode);
                push_heap(heap.begin(),heap.end(), cmp);
            }
        }
    }
}

bool compareDists()
{
    for(int i = 1; i <= n; ++i)
        if(checkDist[i] != d[i])
            return false;
    return true;
}

bool check(int source)
{
    dijkstra(source);
    return compareDists();
}

int main()
{
    int x,y,c;

    f >> t;
    for(int z = 1; z <= t; ++z)
    {
        for(int i = 1; i <= n; ++i) G[i].clear();

        f >> n >> m >> source;
        for(int i = 1; i <= n; ++i) f >> checkDist[i];
        for(int i = 1; i <= m; ++i)
        {
            f >> x >> y >> c;
            G[x].push_back(make_pair(y,c));
            G[y].push_back(make_pair(x,c));
        }

        bool flag = check(source);
        if(flag) g << "DA" << "\n";
        else     g << "NU" << "\n";
    }
    return 0;
}