Hello everyone, I was trying to solve the question on Spoj named Ada and Apple. Here is the link to the problem: https://www.spoj.com/problems/ADAAPPLE/ The following is my solution: I am getting WA after test case 15, I don't know what's wrong... Help me out...
// Code...
include
include
include
include
include
include
include
include
using namespace std; using ll = long long; using ld = long double;
define pb push_back
define eb emplace_back
define ff first
define ss second
define prec(n) fixed << setprecision(n)
const int mxN = 3e5+10; vector adj[mxN]; int n,q,c; int st[mxN],en[mxN]; int t[mxN<<2]; int h[mxN][20]; int d[mxN]; string s; vector test;
void dfs(int u=0,int p=-1,int hi=0){ h[u][0]=p; d[u]=hi; test.pb(u); t[2*n+c]=s[u]-'0'; st[u]=c++; for(auto k:adj[u]){ if(k==p) continue; dfs(k,u,hi+1); } test.pb(u); t[2*n+c]=-(s[u]-'0'); en[u]=c++; }
void build(){ for(int i=2*n-1;i>0;i--){ t[i]=t[i<<1]+t[(i<<1)|1]; } }
void update(int pos,int val){ for(t[pos+=2*n]=val;pos>1;pos>>=1){ t[pos>>1]=t[pos]+t[pos^1]; } }
int query(int l,int r){ int ans=0; for(l+=2*n,r+=2*n;l<r;l>>=1,r>>=1){ if(l&1) ans+=t[l++]; if(r&1) ans+=t[--r]; } return ans; }
int pathLength(int a,int b){ if(d[a] < d[b]) swap(a,b); int diff=d[a]-d[b],temp=a; for(int i=19;i>=0;i--){ if(diff&(1ll<<i)) a=h[a][i]; } if(a==b) return diff+1; for(int i=19;i>=0;i--){ if(h[a][i]!=h[b][i]){ a=h[a][i]; b=h[b][i]; } } return d[b]+d[temp]-2*d[h[a][0]]+1; }
void solve(){ cin >> n >> q; cin >> s; for(int i=0;i<n;i++){ adj[i].clear(); st[i]=0; } for(int i=1,u,v;i<n;i++){ cin >> u >> v; adj[u].pb(v); adj[v].pb(u); } c=0; dfs(); for(int i=1;i<20;i++){ for(int j=0;j<n;j++){ if(h[j][i-1]!=-1) h[j][i]=h[h[j][i-1]][i-1]; else h[j][i]=-1; } } build(); while(q--){ int t; cin >> t; if(t){ int a,b; cin >> a >> b; if(st[a] > st[b]) swap(a,b); int check=query(st[a],st[b]+1); int len=pathLength(a,b); if(check==len || check==0){ cout << "YES\n"; } else{ cout << "NO\n"; } } else{ int a; cin >> a; s[a]='1'-s[a]+'0'; update(st[a],s[a]-'0'); update(en[a],-(s[a]-'0')); } } }
int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); int t=1; // cin >> t; while(t--){ solve(); } return 0; }
Happy coding...




