weak pretests in company queries 2 at cses

Revision en1, by i_hate_pahadans, 2026-01-09 21:45:07

i was constantly getting tle using dfs so i tried this approach just was doing hit and trial

include <bits/stdc++.h>

using namespace std;

define f(i,s,e) for(long long i=s;i<e;i++)

define ll long long

define pii pair<int,int>

define pll pair<ll,ll>

define vi vector

define vll vector

define mii map<int,int>

define si set

define sc set

int main(){ ios::sync_with_stdio(false); cin.tie(NULL);

ll n,q;
cin>>n>>q;

ll LOG=20;

vector<vector<ll>> up(LOG, vector<ll>(n+1));
vll depth(n+1,0);

for(ll i=2;i<=n;i++){
    cin>>up[0][i];
    depth[i]=depth[ up[0][i] ] + 1;
}

for(ll i=1;i<LOG;i++){
    for(ll v=1;v<=n;v++){
        up[i][v]=up[i-1][ up[i-1][v] ];
    }
}

auto lca = [&](ll u,ll v){
    if(depth[u]<depth[v]) swap(u,v);
    ll k=depth[u]-depth[v];
    for(ll i=0;i<LOG;i++){
        if(k&(1LL<<i)) u=up[i][u];
    }
    if(u==v) return u;
    for(ll i=LOG-1;i>=0;i--){
        if(up[i][u]!=up[i][v]){
            u=up[i][u];
            v=up[i][v];
        }
    }
    return up[0][u];
};

while(q--){
    ll u,v;
    cin>>u>>v;
    cout<<lca(u,v)<<"\n";
}

return 0;

} look at the loop where i take input from parent of 2,3,4... but do you notice something in the depth dp that this is true only if the parent of 2 is 1 if parent of 2 is 3 somehow then this always fails always i just uploaded this vague solution and this got surprisngly accepted tho it is conceptually very wronng. [ user : pllk ]

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English i_hate_pahadans 2026-01-09 21:45:07 1703 Initial revision (published)