Cod sursa(job #1891353)

Utilizator Account451Gigel Gogu Account451 Data 23 februarie 2017 22:27:15
Problema Distante Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.73 kb
#include <stdio.h>
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 50005
#define INT_MAX 500000000
using namespace std;

struct edge
{
    int nod,cost;
    edge *next;
};

void add(edge **a, int cost, int from,int where)
{
    edge * p = new edge();
    p->cost = cost;
    p->nod = where;
    p->next = a[from];
    a[from] = p;
}

class Compare
{
    public:
        bool operator() (pair<int, int> a, pair<int, int> b) {
        return b.second < a.second;
    }
};

int djikstra(int x0, int *d, int *dist,int n, edge **a)
{
    priority_queue<pair<int, int>, vector< pair<int,int> >, Compare> q;

    d[x0] = 0;
    q.push(make_pair(x0,0));

    for (int i = 1; i <= n; ++i)
    {
        pair<int, int> min = q.top();
        q.pop();

        edge *p = a[min.first];
        while(p != NULL)
        {
            if(d[p->nod] > min.second + p->cost)
            {
                d[p->nod] = min.second + p->cost;
                q.push(make_pair(p->nod,d[p->nod]));
            }
            p = p->next;
        }
    }

    for(int i = 1; i<= n ;i++)
        if(d[i] != dist[i])
            return 0;
    return 1;
}

int main(void)
{
    int t,n,m,s;
    int d[NMAX], dist[NMAX];
    edge *a[NMAX];

    std::ifstream f("distante.in");
    f>>t;
    std::ofstream g("distante.out");

    for (int j = 0; j < t; ++j)
    {
        f>>n>>m>>s;

        for (int i = 1; i <= n; ++i)
        {
            f>>dist[i];
            a[i] = NULL;
            d[i] = INT_MAX;
        }

        for(int i = 1;i<=m; ++i)
        {
            int x,y,z;
            f>>x>>y>>z;
            add(a,z,x,y),add(a,z,y,x);
        }

        if (djikstra(s, d, dist, n, a))
            g<<"DA\n";
        else
            g<<"NU\n";
    }
    return 0;
}