//LCA cu smenul de la heavypath O(N + M log N) #include #include using namespace std; #define maxn 200010 int l[maxn], niv[maxn], d[maxn], tl[maxn], f[maxn]; int a, b, nl, n, m, x, y, lvl[maxn]; vector v[maxn]; void df(int nod) { f[nod]=1; d[nod]=1; if(v[nod].size()==1 && nod!=1) { l[nod]=++nl; return; } int fmax, it, dmax=0; for(int i=0; idmax) { dmax=d[it]; fmax=(it); } tl[l[it]]=nod; } l[nod]=l[fmax]; } int lca(int x, int y) { while(l[x]!=l[y]) { if(niv[tl[l[x]]]>niv[tl[l[y]]]) x=tl[l[x]]; else y=tl[l[y]]; } if(niv[x]lvl[rez]) rez=sx; if(lvl[sy]>lvl[rez]) rez=sy; if(rez==a || rez==b) printf("-1\n"); else printf("%d\n", rez); } } return 0; }