Cod sursa(job #2968963)

Utilizator Stefan_GhinescuGhinescu Stefan-George Stefan_Ghinescu Data 22 ianuarie 2023 13:47:09
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.82 kb
#include <vector>
#include <queue>
#include <cstring>

#define notlocal 69

#if !notlocal

#include <iostream>
#define fin std::cin
#define fout std::cout

#else

#include <fstream>
std::ifstream fin("dragoni.in");
std::ofstream fout("dragoni.out");

#endif

using namespace std;

const int NMAX = 800;

struct MUCHIE
{
    int nod, cost, drake;
};

bool operator<(const MUCHIE& a, const MUCHIE& b)
{
    if (a.cost == b.cost)
    {
        if (a.drake == b.drake)
        {
            return a.nod > b.nod;
        }
        return a.drake > b.drake;
    }
    return a.cost > b.cost;
}

struct MUCHIE_GRAF
{
    int nod, cost;
};

std::vector <MUCHIE_GRAF>G[NMAX + 5];
int n, /**cost[NMAX + 5],*/ dragon[NMAX + 5], dp[NMAX + 5][NMAX + 5];
bool viz[NMAX + 5];

int bfs_chior(int start)
{
    int maxdrake = dragon[start];
    MUCHIE_GRAF m;
    std::queue <MUCHIE_GRAF> q;
    q.push({start, 0});
    viz[start] = 1;
    while (!q.empty())
    {
        m = q.front();
        q.pop();
        for (MUCHIE_GRAF it : G[m.nod])
        {
            if (!viz[it.nod] && it.cost <= dragon[1])
            {
                maxdrake = max(maxdrake, dragon[it.nod]);
                viz[it.nod] = 1;
                q.push({it.nod, it.cost});
            }
        }
    }
    return maxdrake;
}

void bfs(int start)
{
    bool ok;
    int currentDrake;
    memset(*dp, 0b01111111, sizeof(dp));
    MUCHIE m;
    std::priority_queue <MUCHIE> pq;
    pq.push({start, 0, start});
    dp[start][start] = 0;
    while (!pq.empty())
    {
        m = pq.top();
        currentDrake = m.drake;
        pq.pop();
        for (MUCHIE_GRAF it : G[m.nod])
        {
            currentDrake = m.drake;
            if (dragon[currentDrake] >= it.cost)
            {
                if (dragon[it.nod] > dragon[currentDrake])
                {
                    currentDrake = it.nod;
                }
                if (dp[it.nod][currentDrake] > dp[m.nod][m.drake] + it.cost)
                {
                    dp[it.nod][currentDrake] = dp[m.nod][m.drake] + it.cost;
                    pq.push({it.nod, dp[it.nod][currentDrake], currentDrake});
                }
            }
        }
    }
}

int main()
{
    char p;
    int m, x, y, z;
    fin >> p >> n >> m;
    for (int i = 1; i <= n; ++i)
    {
        fin >> dragon[i];
    }
    for (int i = 0; i < m; ++i)
    {
        fin >> x >> y >> z;
        G[x].push_back({y, z});
        G[y].push_back({x, z});
    }
    if (p == '1')
    {
        fout << bfs_chior(1);
        return 0;
    }
    bfs(1);
    int mini = dp[n][1];
    for (int j = 2; j <= NMAX; ++j)
    {
        if (dp[n][j] < mini)
        {
            mini = dp[n][j];
        }
    }
    fout << mini;
    return 0;
}