import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(to!int).array;
    auto B = readln.split.map!(to!int).array;

    A ~= A.reduce!((a,b) => a^b);
    B ~= B.reduce!((a,b) => a^b);

    if (A.dup.sort() != B.dup.sort()) {
        writeln(-1);
        return;
    }

    auto C = A.dup.sort().uniq.array;
    int M = C.length.to!int;

    int[int] D;
    foreach (i; 0..M) {
        D[C[i]] = i;
    }

    A.each!((ref a) => a = D[a]);
    B.each!((ref a) => a = D[a]);

    auto uf = new UnionFind(M);
    foreach (i; 0..N+1) {
        if (A[i] != B[i]) {
            uf.unite(A[i], B[i]);
            uf.edge[uf.find(A[i])] += 1;
        }
    }


    int ans = 0;

    foreach (i; 0..M) {
        if (uf.find(i) != i) continue;
        if (uf.edge[i] == 0) continue;
        if (uf.find(A.back) == i) {
            ans += uf.edge[i];
            if (A.back != B.back) ans -= 1;
        } else {
            ans += uf.edge[i] + 1;
        }
    }

    ans.writeln;
}



class UnionFind {
    int N;
    int[] table;
    int[] edge;

    this(int n) {
        N = n;
        table = new int[](N);
        fill(table, -1);
        edge = new int[](N);
    }

    int find(int x) {
        return table[x] < 0 ? x : (table[x] = find(table[x]));
    }

    void unite(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        if (table[x] > table[y]) swap(x, y);
        edge[x] += edge[y];
        table[x] += table[y];
        table[y] = x;
    }
}
