#include <bits/stdc++.h>
using namespace std;
vector<int> no, a[200010];
int n, p[200010], q[200010], x, y, s1, s2, an1, an2, an3, an4;
bool ex = 1;
bool get(int x, int fa, int mu) {
  no.emplace_back(x);
  if (x == mu) return 1;
  for (int y : a[x])
    if (y != fa && get(y, x, mu)) return 1;
  no.pop_back();
  return 0;
}
int dis(int x, int y) {
  no.clear();
  get(x, 0, y);
  return no.size() - 1;
}
void dfs(int x, int fa) {
  for (auto y : a[x])
    if (y != fa) dfs(y, x);
  if (p[x] != q[x]) {
    int s = 0;
    for (auto y : a[x])
      if (y != fa && p[y] != q[y]) s++;
    if (s == 0) {
      an3++;
      if (an1)
        an2 = x;
      else {
        an1 = x;
        no.clear();
        get(x, 0, s2);
        for (int i = 0; i < no.size(); i++)
          if (p[no[i]] == q[no[i]]) {
            an2 = an4 = no[i];
            break;
          }
      }
    }
  } else {
    int s = 0;
    for (auto y : a[x])
      if (y != fa && p[y] != q[y]) s++;
    if (s == 2) {
      an3--;
      an4 = x;
    }
  }
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> p[i];
  for (int i = 1; i <= n; i++) cin >> q[i];
  for (int i = 1; i < n; i++) {
    cin >> x >> y;
    a[x].emplace_back(y);
    a[y].emplace_back(x);
  }
  s1 = 0, s2 = 0;
  for (int i = 1; i <= n; i++) {
    if (!p[i]) s1 = i;
    if (!q[i]) s2 = i;
  }
  no.clear();
  get(s1, 0, s2);
  for (int i = 1; i < no.size(); i++) swap(p[no[i - 1]], p[no[i]]);
  int an = 1;
  for (int i = 1; i <= n; i++)
    if (p[i] != q[i]) an = 0;
  if (an) {
    cout << "0 " << dis(s1, s2) << endl;
    return 0;
  }
  dfs(s2, 0);
  if (an3 != 1) {
    cout << "-1" << endl;
    return 0;
  }
  no.clear();
  get(an1, 0, an2);
  for (int i = 0; i < no.size(); i++)
    if (no[i] == an4) no.erase(no.begin() + i);
  int g = 0;
  long long k = no.size();
  for (int i = 0; i < no.size(); i++)
    if (q[no[i]] == p[no[0]]) g = i;
  for (int i = 0; i < no.size(); i++)
    if (p[no[i]] != q[no[(i + g) % no.size()]]) {
      cout << "-1" << endl;
      return 0;
    }
  cout << min(an1, an2) << ' ' << max(an1, an2) << ' '
       << min((k + 1) * (g - 1) + 1 + dis(s1, an1) + dis(s2, an2),
              (k + 1) * (k - g - 1) + 1 + dis(s2, an1) + dis(s1, an2))
       << endl;
  return 0;
}
