i_hate_pahadans's blog

By i_hate_pahadans, history, 8 months ago, In English

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 ]

  • Vote: I like it
  • -28
  • Vote: I do not like it

»
8 months ago, hide # |
Rev. 2  
Vote: I like it -10 Vote: I do not like it
»
8 months ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

One of the input constraints is that $$$1 \le e_i \le i-1$$$, so it is not allowed that 3 is the parent of 2.

»
8 months ago, hide # |
Rev. 2  
Vote: I like it 0 Vote: I do not like it

In general, on CSES, if you think you found a test case where an accepted submission fails, you can hack that submission, and the test case might later be added to the official test set.