#include <bits/stdc++.h>
using namespace std;
const int maxn = 200005;
vector<int> sosedi[maxn];
int parent[maxn], shagi[maxn], start[maxn], finish[maxn], n;
bool visit_vertex[maxn];
void dfs(int v, int predok) {
  parent[v] = predok;
  shagi[v] = shagi[predok] + 1;
  for (auto p : sosedi[v])
    if (p != predok) dfs(p, v);
}
vector<int> circles;
int rt, st1, end1;
bool find_circle() {
  circles.clear();
  int p = 0;
  for (int i = 1; i <= n; i++)
    if (start[i] != finish[i] && shagi[i] > shagi[p]) p = i;
  if (!p) return 1;
  for (int u = p; visit_vertex[u] = 1, circles.push_back(u),
           start[parent[u]] != finish[parent[u]];
       u = parent[u])
    ;
  int q = 0;
  for (int i = 1; i <= n; i++)
    if (start[i] != finish[i] && !visit_vertex[i] && shagi[i] > shagi[q]) q = i;
  if (q) {
    reverse(circles.begin(), circles.end());
    for (int u = q; visit_vertex[u] = 1, circles.push_back(u),
             start[parent[u]] != finish[parent[u]];
         u = parent[u])
      ;
  } else
    q = parent[circles.back()];
  for (int i = 1; i <= n; i++)
    if (start[i] != finish[i] && !visit_vertex[i]) return 0;
  int u, v;
  for (u = p, v = q; u != v; u = parent[u])
    if (shagi[u] < shagi[v]) swap(u, v);
  rt = u;
  if (circles.size() != shagi[p] + shagi[q] - 2 * shagi[rt]) return 0;
  st1 = p, end1 = q;
  return 1;
}
int main() {
  cin >> n;
  int pa, pb;
  for (int i = 1; i <= n; i++) {
    cin >> start[i];
    if (start[i] == 0) pa = i;
  }
  for (int i = 1; i <= n; i++) {
    cin >> finish[i];
    if (finish[i] == 0) pb = i;
  }
  for (int i = 1, u, v; i < n; i++) {
    cin >> u >> v;
    sosedi[u].push_back(v), sosedi[v].push_back(u);
  }
  shagi[0] = -1;
  dfs(pb, 0);
  for (int u = pa; u != pb; u = parent[u]) swap(start[u], start[parent[u]]);
  long long answer = shagi[pa];
  if (!find_circle()) {
    cout << -1 << endl;
    return 0;
  }
  if (!circles.size()) {
    cout << 0 << " " << answer << " " << endl;
    return 0;
  }
  int gap = 0, len = circles.size();
  for (int i = 0; i < len; i++)
    if (finish[circles[i]] == start[circles[0]]) gap = i;
  for (int i = 1; i < len; i++)
    if (finish[circles[(i + gap) % len]] != start[circles[i]]) {
      printf("-1\n");
      return 0;
    }
  memset(visit_vertex, false, maxn);
  for (int i = pa; i; i = parent[i]) visit_vertex[i] = 1;
  if (visit_vertex[circles[0]] || visit_vertex[circles.back()]) {
    int po = circles.size();
    for (int i = 0; i < circles.size(); i++)
      if (!visit_vertex[circles[i]]) {
        po = i;
        break;
      }
    answer = answer - po +
             min(po + gap * 1ll * (len + 1),
                 abs((len - gap) * 1ll * (len + 1) - po));
  } else
    answer = (answer + min(gap, len - gap) * 1ll * (len + 1));
  for (; !visit_vertex[rt]; rt = parent[rt]) answer += 2;
  if (st1 > end1) swap(end1, st1);
  cout << st1 << " " << end1 << " " << answer << " " << endl;
  return 0;
}
