#include <bits/stdc++.h>
using namespace std;
int n, S, T, a[200050], b[200050], anc[200050], dep[200050], head[200050];
bool in[200050];
bool mark[200050];
vector<int> v;
struct edge {
  int to, nex;
  edge(int to = 0, int nex = 0) : to(to), nex(nex) {}
};
vector<edge> G;
void addedge(int u, int v) {
  G.push_back(edge(v, head[u])), head[u] = G.size() - 1;
  G.push_back(edge(u, head[v])), head[v] = G.size() - 1;
}
void dfs(int u) {
  for (int i = head[u]; ~i; i = G[i].nex) {
    int v = G[i].to;
    if (v != anc[u]) {
      anc[v] = u;
      dep[v] = dep[u] + 1;
      dfs(v);
    }
  }
}
bool solve() {
  dfs(T);
  for (int u = S;; u = anc[u]) {
    mark[u] = 1;
    if (u == T) {
      break;
    } else {
      swap(a[u], a[anc[u]]);
    }
  }
  int s1 = -1, p = -1;
  int s2 = -1, q = -1;
  for (int i = 1; i <= n; ++i)
    if (a[i] != b[i]) {
      if (s1 == -1 || dep[s1] < dep[i]) {
        s1 = i;
      }
    }
  if (s1 == -1) {
    printf("0 %d\n", dep[S]);
    return true;
  }
  for (p = s1; a[p] != b[p]; p = anc[p]) {
    v.push_back(p);
    in[p] = 1;
  }
  int m = v.size();
  for (int i = 1; i <= n; ++i)
    if (!in[i] && a[i] != b[i]) {
      if (s2 == -1 || dep[s2] < dep[i]) {
        s2 = i;
      }
    }
  if (s2 != -1) {
    for (q = s2; a[q] != b[q]; q = anc[q]) {
      if (in[q]) {
        return false;
      }
      v.push_back(q);
      in[q] = 1;
    }
    if (p != q) {
      return false;
    }
    reverse(v.begin() + m, v.end());
  } else {
    s2 = p;
  }
  for (int i = 1; i <= n; ++i)
    if (a[i] != b[i]) {
      if (!in[i]) {
        return false;
      }
    }
  int M = v.size();
  int d = -1;
  for (int i = 1; i < M; ++i) {
    if (b[v[i]] == a[v[0]]) {
      d = i;
      break;
    }
  }
  assert(d != -1);
  for (int i = 0; i < M; ++i) {
    if (a[v[i]] != b[v[(i + d) % M]]) {
      return false;
    }
  }
  printf("%d %d ", min(s1, s2), max(s1, s2));
  int cnt = 0;
  for (int i = 0; i < M; ++i) {
    if (mark[v[i]]) {
      ++cnt;
    }
  }
  long long an = dep[S];
  if (cnt == 0) {
    an += (long long)min(d, M - d) * (M + 1);
    while (!mark[p]) {
      an += 2;
      p = anc[p];
    }
  } else {
    for (int i = m; i < M; ++i) {
      if (mark[v[i]]) {
        d = M - d;
        break;
      }
    }
    an +=
        min((long long)d * (M + 1) - (cnt << 1), (long long)(M - d) * (M + 1));
  }
  printf("%I64d\n", an);
  return true;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &a[i]);
    if (a[i] == 0) {
      S = i;
    }
  }
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &b[i]);
    if (b[i] == 0) {
      T = i;
    }
  }
  memset(head, -1, sizeof(head));
  for (int i = 1; i < n; ++i) {
    int u, v;
    scanf("%d%d", &u, &v);
    addedge(u, v);
  }
  if (!solve()) {
    printf("-1\n");
  }
  return 0;
}
