Cod sursa(job #3299919)

Utilizator rapidu36Victor Manz rapidu36 Data 11 iunie 2025 19:08:50
Problema Atac Scor 20
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.72 kb
#include <fstream>
#include <vector>
#include <cmath>

using namespace std;

const int INF = 2e9;

vector <vector <pair <int, int>>> a;
vector <vector <int>> s;
vector <vector <int>> cost;
vector <int> t_in;
vector <int> t_out;
int timp;
int log_2_n;

void dfs(int x, int t)
{
    t_in[x] = ++timp;
    for (auto p: a[x])
    {
        int vf = p.first;
        int c = p.second;
        if (vf != t)
        {
            s[0][vf] = x;
            cost[0][vf] = c;
            dfs(vf, x);
        }
    }
    t_out[x] = ++timp;
}

bool e_stramos(int x, int y)
{
    return (t_in[x] <= t_in[y] && t_out[y] <= t_out[x]);
}

int cost_lca(int x, int y)
{
    int s_com;
    if (e_stramos(x, y))
    {
        s_com = x;
    }
    else
    {
        int x_ = x;
        for (int i = log_2_n; i >= 0; i--)
        {
            if (s[i][x] != 0 && !e_stramos(s[i][x], y))
            {
                x = s[i][x];
            }
        }
        s_com = s[0][x];
        x = x_;
    }
    int c_com = INF;
    for (int i = log_2_n; i >= 0; i--)
    {
        if (s[i][x] != 0 && (s[i][x] == s_com || !e_stramos(s[i][x], s_com)))
        {
            c_com = min(c_com, cost[i][x]);
            x = s[i][x];
        }
    }
    for (int i = log_2_n; i >= 0; i--)
    {
        if (s[i][y] != 0 && (s[i][y] == s_com || !e_stramos(s[i][y], s_com)))
        {
            c_com = min(c_com, cost[i][y]);
            y = s[i][y];
        }
    }
    return c_com;
}

int main()
{
    ifstream in("atac.in");
    ofstream out("atac.out");
    int n, m, p;
    in >> n >> m >> p;
    log_2_n = (int)log2(n);
    s.resize(log_2_n + 1);
    cost.resize(log_2_n + 1);
    for (int i = 0; i <= log_2_n; i++)
    {
        s[i].resize(n + 1, 0);
        cost[i].resize(n + 1, INF);
    }
    a.resize(n + 1);
    for (int i = 2; i <= n; i++)
    {
        int j, c;
        in >> j >> c;
        a[i].push_back({j, c});
        a[j].push_back({i, c});
    }
    t_in.resize(n + 1);
    t_out.resize(n + 1);
    timp = 0;
    dfs(1, 0);
    for (int i = 1; i <= log_2_n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            s[i][j] = s[i-1][s[i-1][j]];
            cost[i][j] = min(cost[i-1][j], cost[i-1][s[i-1][j]]);
        }
    }
    int x, y, a, b, c, d;
    in >> x >> y >> a >> b >> c >> d;
    for (int i = 0; i < m; i++)
    {
        int cost_com;
        cost_com = cost_lca(x, y);
        if (i >= m - p)
        {
            out << cost_com << "\n";
        }
        int x_ = (a * x + b * y) % n + 1;
        int y_ = (c * y + d * cost_com) % n + 1;
        x = x_;
        y = y_;
    }
    in.close();
    out.close();
    return 0;
}