hdu 5495 LCS (置换群)
Sample Input
2
3
1 2 3
3 2 1
6
1 5 3 2 6 4
3 6 2 4 5 1
Sample Output
2
4
2
4
C/C++:
1 #include <map> 2 #include <queue> 3 #include <cmath> 4 #include <vector> 5 #include <string> 6 #include <cstdio> 7 #include <cstring> 8 #include <climits> 9 #include <iostream> 10 #include <algorithm> 11 #define INF 0x3f3f3f3f 12 #define LL long long 13 using namespace std; 14 const int MAX = 1e5 + 10; 15 16 int a[MAX], b[MAX], c[MAX], vis[MAX], n, t, ans; 17 18 int main() 19 { 20 scanf("%d", &t); 21 while (t --) 22 { 23 scanf("%d", &n); 24 for (int i = 1; i <= n; ++ i) 25 { 26 scanf("%d", &a[i]); 27 vis[i] = 0; 28 } 29 for (int i = 1; i <= n; ++ i) 30 scanf("%d", &b[i]); 31 for (int i = 1; i <= n; ++ i) 32 c[a[i]] = b[i]; 33 34 ans = n; 35 for (int i = 1; i <= n; ++ i) 36 { 37 int temp = i; 38 if (vis[temp]) continue; 39 if (temp != c[temp]) 40 { 41 ans --; 42 while (!vis[temp]) 43 { 44 vis[temp] = 1; 45 temp = c[temp]; 46 } 47 } 48 } 49 printf("%d\n", ans); 50 } 51 return 0; 52 }