#include <bits/stdc++.h>
inline long long min(long long x, long long y) { return x < y ? x : y; }
int A[200002], B[200002], a[200002], O[200002], P[200002], Q, b[400004],
    c[400004], f[200002], h[200002], n, s, t;
bool d[200002];
inline int dis(int u, int v) {
  int w = 0;
  for (; u != v; h[u] < h[v] ? v = f[v] : u = f[u]) w++;
  return w;
}
void dfs(int u) {
  for (int i = a[u]; i; i = b[i])
    if (c[i] != f[u]) f[c[i]] = u, h[c[i]] = h[u] + 1, dfs(c[i]);
}
int i, u, v, w;
int main() {
  scanf("%d", &n);
  for (i = 1; i <= n; i++) scanf("%d", A + i);
  for (i = 1; i <= n; i++) scanf("%d", B + i);
  for (i = 1; i < n; i++)
    scanf("%d%d", &u, &v), b[++t] = a[u], c[a[u] = t] = v, b[++t] = a[v],
                           c[a[v] = t] = u;
  for (i = 1, u = 0; i <= n; i++) s = !A[i] ? i : s, t = !B[i] ? i : t;
  for (dfs(t), i = s; i; i = f[i]) A[i] = A[f[i]];
  for (i = 1; i <= n; i++)
    if (A[i] != B[i] && h[u] < h[i]) u = i;
  if (!u) return 0 & printf("0 %d\n", h[s]);
  for (i = u; i; i = f[i]) d[i] = true, w = A[i] != B[i] ? i : w;
  for (i = 1, v = w = f[w]; i <= n; i++)
    if (!d[i] && A[i] != B[i] && h[v] <= h[i]) v = i;
  for (i = v; !d[i]; i = f[i]) d[i] = true;
  if (i != w) return 0 & puts("-1");
  for (i = 1; i <= n; i++)
    if (!d[i] && A[i] != B[i]) return 0 & puts("-1");
  for (i = u; i != w; i = f[i]) O[++Q] = A[i], P[Q] = B[i];
  for (i = 1; i << 1 <= Q; i++)
    O[i] ^= O[Q - i + 1] ^= O[i] ^= O[Q - i + 1],
        P[i] ^= P[Q - i + 1] ^= P[i] ^= P[Q - i + 1];
  for (i = v; i != w; i = f[i]) O[++Q] = A[i], P[Q] = B[i];
  for (i = 1, w = 0; !w; i++)
    if (O[1] == P[i]) w = i;
  for (i = 0; i <= Q - w; i++)
    if (O[i + 1] != P[w + i]) return 0 & puts("-1");
  for (; i < Q; i++)
    if (O[i + 1] != P[i - Q + w]) return 0 & puts("-1");
  return 0 * printf("%d %d %d\n", u < v ? u : v, u < v ? v : u,
                    min(dis(s, u) + (Q + 1ll) * (Q - w) + dis(v, t) + 1,
                        dis(s, v) + (Q + 1ll) * (w - 2) + dis(u, t) + 1));
}
