CSES - Aalto Competitive Programming 2024 - wk7 Homework - Results
Submission details
Task:Company Queries II
Sender:ilyas.ben
Submission time:2024-10-24 19:36:35 +0300
Language:C++ (C++20)
Status:COMPILE ERROR

Compiler report

input/code.cpp: In function 'int main()':
input/code.cpp:77:14: error: expected '}' at end of input
   77 |     return 0;
      |              ^
input/code.cpp:54:12: note: to match this '{'
   54 | int main() {
      |            ^

Code

#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
const int MAXN = 200001;
const int LOG = 18;
 
vector<int> adj[MAXN];
int up[MAXN][LOG]; 
int depth[MAXN];
 
void dfs(int v, int parent) {
    up[v][0] = parent; 
    for (int i = 1; i < LOG; i++) {
        if (up[v][i - 1] != -1) {
            up[v][i] = up[up[v][i - 1]][i - 1]; 
        } else {
            up[v][i] = -1;
        }
    }
 
    for (int u : adj[v]) {
        if (u != parent) {
            depth[u] = depth[v] + 1;
            dfs(u, v);
        }
    }
}
 
int lca(int a, int b) {
    if (depth[a] < depth[b]) swap(a, b);
 
    
    for (int i = LOG - 1; i >= 0; i--) {
        if (depth[a] - (1 << i) >= depth[b]) {
            a = up[a][i];
        }
    }
 
    if (a == b) return a;
 
    for (int i = LOG - 1; i >= 0; i--) {
        if (up[a][i] != up[b][i]) {
            a = up[a][i];
            b = up[b][i];
        }
    }
 
    return up[a][0];
}
 
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
 
    int n, q;
    cin >> n >> q;
 
    for (int i = 2; i <= n; i++) {
        int boss;
        cin >> boss;
        adj[boss].push_back(i);
        adj[i].push_back(boss);
    }
 
    depth[1] = 0;
    dfs(1, -1);
 
     while (q--) {
        int a, b;
        cin >> a >> b;
        cout << lca(a, b) << "\n";
    }
 
    return 0;