#include <bits/stdc++.h>
using namespace std;
const int N = 200100;
vector<int> g[N];
int a[N], b[N], p[N], q[N], n, s, t, ans_u, ans_v, cnt;
void gofail() {
  cout << -1 << '\n';
  exit(0);
}
int chk(int* a, int* b, int n) {
  for (int i = 1; i <= n; ++i)
    if (b[i] == a[1]) {
      for (int j = 0; j < n; ++j)
        if (a[j % n + 1] != b[(i - 1 + j) % n + 1]) return -1;
      return i - 1;
    }
  return -1;
}
int fa[N], dp[N];
void dfs(int x) {
  for (int i : g[x])
    if (i != fa[x]) {
      fa[i] = x;
      dp[i] = dp[x] + 1;
      dfs(i);
    }
}
int lca(int x, int y) {
  for (; x != y; x = fa[x])
    if (dp[x] < dp[y]) swap(x, y);
  return x;
}
int dis(int x, int y) { return dp[x] + dp[y] - 2 * dp[lca(x, y)]; }
int vis[N];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i];
    if (!a[i]) s = i;
  }
  for (int i = 1; i <= n; ++i) {
    cin >> b[i];
    if (!b[i]) t = i;
  }
  for (int i = 1; i < n; ++i) {
    int x, y;
    cin >> x >> y;
    g[x].push_back(y);
    g[y].push_back(x);
  }
  dfs(t);
  int rs = s;
  for (; s != t; s = fa[s]) swap(a[s], a[fa[s]]);
  int lst = 0, hst = 0;
  for (int i = 1; i <= n; ++i)
    if (a[i] != b[i]) {
      ++cnt;
      if (!lst || dp[i] > dp[lst]) lst = i;
      if (!hst || dp[i] < dp[hst]) hst = i;
    }
  if (!lst) {
    cout << 0 << ' ' << dis(rs, t) << '\n';
    return 0;
  }
  if (hst == t) gofail();
  hst = fa[hst];
  int tt = 0, ww = cnt + 1;
  for (int i = lst; i && i != hst; i = fa[i]) {
    if (a[i] == b[i]) gofail();
    p[++tt] = a[i];
    q[tt] = b[i];
    vis[i] = 1;
  }
  ans_u = lst;
  lst = 0;
  for (int i = 1; i <= n; ++i)
    if (a[i] != b[i] && !vis[i] && (!lst || dp[i] > dp[lst])) lst = i;
  if (!lst)
    ans_v = hst;
  else {
    for (int i = lst; i && i != hst; i = fa[i]) {
      if (a[i] == b[i] || vis[i]) gofail();
      p[--ww] = a[i];
      q[ww] = b[i];
      vis[i] = 1;
    }
    if (tt + 1 != ww) gofail();
    ans_v = lst;
  }
  if (ans_u > ans_v) {
    swap(ans_u, ans_v);
    reverse(p + 1, p + cnt + 1);
    reverse(q + 1, q + cnt + 1);
  }
  int res = chk(p, q, cnt);
  if (res == -1) gofail();
  cout << ans_u << ' ' << ans_v << ' '
       << min(dis(rs, ans_u) + (long long)(res - 1) * (dis(ans_v, ans_u) + 1) +
                  1 + dis(ans_v, t),
              dis(rs, ans_v) +
                  (long long)(cnt - res - 1) * (dis(ans_v, ans_u) + 1) + 1 +
                  dis(ans_u, t))
       << '\n';
  return 0;
}
