Cod sursa(job #3002096)

Utilizator CaptnBananaPetcu Tudor CaptnBanana Data 14 martie 2023 12:39:49
Problema Distante Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.04 kb
#include <bits/stdc++.h>

using namespace std;

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

const int N = 5e4 + 1, INF32 = 0x3f3f3f3f;
int t, n, m, s, x, y, w, nh;
int h[N], d[N], d_adev[N];
vector<pair<int, int>> c[N];
bool in_heap[N];

void urca(int p){
    while(p / 2 && d_adev[h[p]] < d_adev[h[p / 2]]){
        swap(h[p], h[p / 2]);
        p /= 2;
    }
}

void coboara(int p){
    int fs = 2 * p, fd = 2 * p + 1, bun = p;
    if(fs <= nh && d_adev[h[bun]] > d_adev[h[fs]])
        bun = fs;

    if(fd <= nh && d_adev[h[bun]] > d_adev[h[fd]])
        bun = fd;

    if(bun != p){
        swap(h[bun], h[p]);
        coboara(bun);
    }
}

void sterge(int p){
    in_heap[h[p]] = false;
    h[p] = h[nh--];
    coboara(p);
}

void dijkstra(int s){
    for(int i = 1; i <= N; i++){
        d_adev[i] = INF32;
        in_heap[i] = false;
    }

    d_adev[s] = 0;
    h[++nh] = s;
    in_heap[s] = true;
    while(nh){
        int x = h[1];
        sterge(1);
        for(auto e: c[x]){
            int y = e.first, w = e.second;
            if(d_adev[x] + w < d_adev[y]){
                d_adev[y] = d_adev[x] + w;
                if(!in_heap[y]){
                    h[++nh] = y;
                    in_heap[y] = true;
                }

                urca(nh); // coboara nu trb. pt. ca nu are cum sa fie mai rea distanta, doar mai buna
            }
        }
    }
}

int main(){
    f >> t;
    while(t--){
        f >> n >> m >> s;
        for(int i = 1; i <= n; i++){
            f >> d[i];
            c[i].clear();
        }

        for(int i = 0; i < m; i++){
            f >> x >> y >> w;
            c[x].push_back({y, w});
            c[y].push_back({x, w});
        }

        dijkstra(s);
        bool adevarat = true;
        for(int i = 1; i <= n; i++){
            if(d[i] != d_adev[i]){
                adevarat = false;
                break;
            }
        }

        g << (adevarat ? "DA" : "NU") << '\n';
    }

    f.close();
    g.close();
}