class UnionFind: def __init__(self, size): self.data = [-1] * size def root(self, x): if self.data[x] < 0: return x ans = self.root(self.data[x]) self.data[x] = ans return ans def unite(self, x, y): x = self.root(x) y = self.root(y) if x == y: return False if self.data[x] > self.data[y]: x, y = y, x self.data[x] += self.data[y] self.data[y] = x return True def is_root(self, x): return self.data[x] < 0 def size(self, x): return -self.data[self.root(x)] n, m = map(int, input().split(' ')) assert 1 <= n <= 200000 assert 1 <= m <= 200000 b = [*map(int, input().split(' '))] assert len(b) == n for i in b: assert 1 <= i <= m c = [*map(int, input().split(' '))] assert len(c) == n for i in c: assert 1 <= i <= n for i in range(n): b[i] -= 1 c[i] -= 1 uf = UnionFind(n + m) # n + i に色 i の超頂点をおく for i in range(n): uf.unite(b[i], m + c[i]) ans = 0 for i in range(n + m): if uf.is_root(i): ans += uf.size(i) - 1 for i in range(m, m + n): # 超頂点の分足しすぎるので、引く if uf.size(i) > 1: ans -= 1 print(ans)