要把某一个套娃从某一个中拿出来,往另一个中放的时候,也要把另一个的外围全部拿开
这样我们以 a [ ] 为当前套娃的状态,,先扫一遍 a [ ] ,把不合状态的套娃全部拿出来,然后按照给定的状态相互嵌套就是了
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <sstream>
#define PI acos(-1.0)
#define in freopen("in.txt", "r", stdin)
#define out freopen("out.txt", "w", stdout)
using namespace std;
const int maxn = 100000 + 7, INF = 0x3f3f3f3f, mod = 1e9 + 7;
int n;
int a[maxn], b[maxn];
void init() {
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
}
for(int i = 1; i <= n; ++i) {
scanf("%d", &b[i]);
}
}
int dfs1(int id) {
int ans = 0, i = id;
while(a[i]) {
ans++;
int t = i;
i = a[i];
a[t] = 0;
}
return ans;
}
int dfs2(int id) {
int ans = 0, i = b[id];
if(i) ans ++;
else return 0;
while(a[i]) {
ans++;
int t= i;
i = a[i];
a[t] = 0;
}
return ans;
}
int main() {
while(scanf("%d", &n) != EOF && n) {
init();
int ans = 0;
for(int i = 1; i <= n; ++i) {
if(a[i] == b[i]) continue;
else {
ans += dfs1(i);
}
}
for(int i = 1; i <= n; ++i) {
if(a[i] != b[i]) {
ans += dfs2(i);
a[i] = b[i];
}
}
cout << ans << endl;
}
return 0;
}