Cod sursa(job #3317277)

Utilizator Rodik_RodyRodica Vasilescu Rodik_Rody Data 23 octombrie 2025 00:27:32
Problema Lowest Common Ancestor Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.38 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

struct Node {
    int value;
    vector<Node*> children;

    Node(int val) : value(val) {}
};

Node* findNode(Node* node, int value) {
    if (node->value == value) return node;

    for (Node* child : node->children) {
        Node* result = findNode(child, value);
        if (result != nullptr) return result;
    }

    return nullptr;
}

void addNode(Node* root, int parentValue, int childValue) {
    Node* parent = findNode(root, parentValue);
    if (parent != nullptr) {
        parent->children.push_back(new Node(childValue));
    }
}

vector<int> getAllChildren(Node* node) {
    vector<int> childrenValues;
    childrenValues.push_back(node->value);

    for (Node* child : node->children) {
        childrenValues.push_back(child->value);
        vector<int> subChildren = getAllChildren(child);
        childrenValues.insert(childrenValues.end(), subChildren.begin(), subChildren.end());
    }

    return childrenValues;
}

int LCA(Node* node, int node1, int node2) {
    int solution = -1;
    vector<int> childrenValues = getAllChildren(node);

    if (find(childrenValues.begin(), childrenValues.end(), node1) != childrenValues.end() &&
        find(childrenValues.begin(), childrenValues.end(), node2) != childrenValues.end()) {
        solution = node->value;
    }

    for (Node* child : node->children) {
        int newSolution = LCA(child, node1, node2);
        if (newSolution != -1) solution = newSolution;
    }

    return solution;
}

int main() {
    ifstream fin("lca.in");
    ofstream fout("lca.out");

    string line;
    getline(fin, line);
    stringstream ss(line);

    int n, q;
    ss >> n >> q;

    vector<int> parents(n - 1);
    getline(fin, line);
    ss.clear();
    ss.str(line);
    for (int i = 0; i < n - 1; i++) {
        ss >> parents[i];
    }

    Node* root = new Node(1);

    for (int i = 0; i < n - 1; i++) {
        addNode(root, parents[i], i + 2);
    }

    for (int i = 0; i < q; i++) {
        getline(fin, line);
        ss.clear();
        ss.str(line);
        int u, v;
        ss >> u >> v;
        int result = LCA(root, u, v);
        fout << result << "\n";
    }

    fin.close();
    fout.close();

    return 0;
}