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 62 63 64 65
| #include<cstdio> #include<algorithm> #include<cctype> #include<string.h> #include<cmath> #include<vector>
using namespace std; #define ll long long
inline char read() { static const int IN_LEN = 1000000; static char buf[IN_LEN], *s, *t; return (s==t?t=(s=buf)+fread(buf,1,IN_LEN,stdin),(s==t?-1:*s++):*s++); } template<class T> inline void read(T &x) { static bool iosig; static char c; for (iosig=false, c=read(); !isdigit(c); c=read()) { if (c == '-') iosig=true; if (c == -1) return; } for (x=0; isdigit(c); c=read()) x=((x+(x<<2))<<1)+(c^'0'); if (iosig) x=-x; }
const int N = 200005; int n, x, y, ans, top[N], dep[N], fa[N], siz[N], d[N]; bool vis[N]; vector<int> a[N], b[N]; void dfs1(int u){ siz[u]=1; for(int v:b[u]) if(v!=fa[u]) dep[v]=dep[u]+1, fa[v]=u, dfs1(v), siz[u]+=siz[v]; } void dfs2(int u){ int son=0; for(int v:b[u]) if(v!=fa[u] && siz[v]>siz[son]) son=v; if(son) top[son]=top[u], dfs2(son); for(int v:b[u]) if(v!=fa[u] && v!=son) top[v]=v, dfs2(v); } void dfs3(int u, int fa=0){ if(vis[u] && d[u]<dep[u]){ puts("-1"); exit(0); } if(d[u]>=dep[u]) return; ans=max(ans, dep[u]); for(int v:a[u]) if(v!=fa) d[v]=d[u]+1, dfs3(v, u); } inline int dis(int x, int y){ int ans=dep[x]+dep[y]; while(top[x]!=top[y]) if(dep[top[x]]<dep[top[y]]) y=fa[top[y]]; else x=fa[top[x]]; return ans-min(dep[x], dep[y])*2; } int main() { read(n), read(x), read(y); for(int i=1, u, v; i<n; ++i) read(u), read(v), a[u].push_back(v), a[v].push_back(u); for(int i=1, u, v; i<n; ++i) read(u), read(v), b[u].push_back(v), b[v].push_back(u); dfs1(y), top[y]=y, dfs2(y); for(int i=1; i<=n; ++i) for(int j:a[i]) if(i<j) if(dis(i, j)>2) vis[i]=vis[j]=1; dfs3(x); return printf("%d", ans<<1), 0; }
|