#include <bits/stdc++.h>   using namespace std;   const int maxn = 200005;   vector<int> lk[maxn];   int fa[maxn], dep[maxn], a[maxn], b[maxn], n;   void dfs(int now, int pre) {     fa[now] = pre;     dep[now] = dep[pre] + 1;     for (auto p : lk[now])       if (p != pre) dfs(p, now);   }   vector<int> cir;   int rt, lp, lq;   bool find_circle() {     cir.clear();     static bool vis[maxn];     int p = 0;     for (int i = 1; i <= n; i++)       if (a[i] != b[i] && dep[i] > dep[p]) p = i;     if (!p) return 1;     for (int u = p; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]]; u = fa[u])       ;     int q = 0;     for (int i = 1; i <= n; i++)       if (a[i] != b[i] && !vis[i] && dep[i] > dep[q]) q = i;     if (q) {       reverse(cir.begin(), cir.end());       for (int u = q; vis[u] = 1, cir.push_back(u), a[fa[u]] != b[fa[u]];            u = fa[u])         ;     } else       q = fa[cir.back()];     for (int i = 1; i <= n; i++)       if (a[i] != b[i] && !vis[i]) return 0;     int u, v;     for (u = p, v = q; u != v; u = fa[u])       if (dep[u] < dep[v]) swap(u, v);     rt = u;     if (cir.size() != dep[p] + dep[q] - 2 * dep[rt]) return 0;     lp = p, lq = q;     return 1;   }   int main() {     scanf( %d , &n);     for (int i = 1; i <= n; i++) scanf( %d , &a[i]);     for (int i = 1; i <= n; i++) scanf( %d , &b[i]);     for (int i = 1, u, v; i < n; i++) {       scanf( %d%d , &u, &v);       lk[u].push_back(v), lk[v].push_back(u);     }     int pa = find(a + 1, a + n + 1, 0) - a, pb = find(b + 1, b + n + 1, 0) - b;     dep[0] = -1;     dfs(pb, 0);     for (int u = pa; u != pb; u = fa[u]) swap(a[u], a[fa[u]]);     long long ans = dep[pa];     if (!find_circle()) {       printf( -1 n );       return 0;     }     if (!cir.size()) {       printf( 0 %d n , ans);       return 0;     }     int gap = 0, len = cir.size();     for (int i = 0; i < len; i++)       if (b[cir[i]] == a[cir[0]]) gap = i;     for (int i = 1; i < len; i++)       if (b[cir[(i + gap) % len]] != a[cir[i]]) {         printf( -1 n );         return 0;       }     static bool vis[maxn];     for (int i = pa; i; i = fa[i]) vis[i] = 1;     if (vis[cir[0]] || vis[cir.back()]) {       if (vis[cir.back()]) reverse(cir.begin(), cir.end()), gap = len - gap;       int po = cir.size();       for (int i = 0; i < cir.size(); i++)         if (!vis[cir[i]]) {           po = i;           break;         }       ans = ans - po +             min(po + gap * 1ll * (len + 1),                 abs((len - gap) * 1ll * (len + 1) - po));     } else       ans = (ans + min(gap, len - gap) * 1ll * (len + 1));     for (; !vis[rt]; rt = fa[rt]) ans += 2;     if (lp > lq) swap(lq, lp);     printf( %d %d %lld n , lp, lq, ans);     return 0;   }   