#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
vector<int> V[200010], cir;
int fa[200010], dep[200010], a[200010], b[200010], n, Rt, lp, lq, pa, pb;
void dfs(int rt, int pr) {
  for (int i = 0; i < V[rt].size(); i++) {
    if (V[rt][i] == pr) continue;
    fa[V[rt][i]] = rt;
    dep[V[rt][i]] = dep[rt] + 1;
    dfs(V[rt][i], rt);
  }
}
bool findloop() {
  cir.clear();
  bool vis[200010];
  memset(vis, 0, sizeof vis);
  int p = 0, q = 0, u, v;
  ;
  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])
    ;
  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;
  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() {
  n = read();
  for (int i = 1; i <= n; i++) a[i] = read(), pa = a[i] == 0 ? i : pa;
  for (int i = 1; i <= n; i++) b[i] = read(), pb = b[i] == 0 ? i : pb;
  for (int i = 1, u, v; i < n; i++)
    u = read(), v = read(), V[u].push_back(v), V[v].push_back(u);
  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 (!findloop()) {
    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;
  static bool vis[200010];
  for (int i = pa; i; i = fa[i]) vis[i] = 1;
  if (vis[cir[0]] || vis[cir.back()]) {
    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;
}
