1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| const int N=2e5+5; struct Edge{ int next,to; Edge(int next=0,int to=0):next(next),to(to){}; }edge[N<<2]; int ha[N],hb[N],tot; int fa[N],hson[N],Size[N],top[N],depth[N]; int ans,cir,n,a,b;
inline void _add(int *head,int x,int y){ edge[++tot]=Edge(head[x],y);head[x]=tot;} inline void add(int *head,int x,int y){ _add(head,x,y); _add(head,y,x);}
void dfs1(int x){ Size[x]=1; for(rei i=hb[x];i;i=edge[i].next){ rei y=edge[i].to; if(y==fa[x]) continue; depth[y]=depth[x]+1,fa[y]=x; dfs1(y), Size[x]+=Size[y],hson[x]=Size[ hson[x] ]>Size[y] ? hson[x] : y; } }
inline int lca(int x,int y){ while(top[x]!=top[y]){ if(depth[ top[x] ]<depth[ top[y] ]) x^=y,y^=x,x^=y; x=fa[ top[x] ]; } return depth[x]<depth[y] ? x : y; }
inline int dis(int x,int y){ return depth[x]+depth[y]-2*depth[ lca(x,y) ];}
void dfs2(int x,int anc){ top[x]=anc; if(hson[x]) dfs2(hson[x],anc); for(rei i=hb[x];i;i=edge[i].next){ rei y=edge[i].to; if(y!=fa[x] && y!=hson[x]) dfs2(y,y); } }
void escape(int x,int fa,int dep){ ans=max(ans,depth[x]<<1); for(rei i=ha[x];i;i=edge[i].next){ rei y=edge[i].to; if(dis(x,y)>2) cir=1; if(y==fa || dep+1>=depth[y]) continue; escape(y,x,dep+1); } }
int main(){ scanf("%d%d%d",&n,&a,&b); for(rei i=1,x,y;i<n;++i) scanf("%d%d",&x,&y),add(ha,x,y); for(rei i=1,x,y;i<n;++i) scanf("%d%d",&x,&y),add(hb,x,y); dfs1(b);dfs2(b,b); escape(a,0,0); printf("%d\n",cir ? -1 : ans); getchar(),getchar(); return 0; }
|
Gitalking ...