LCS
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 682 Accepted Submission(s): 370
Total Submission(s): 682 Accepted Submission(s): 370
Problem Description
You are given two sequence
{a1,a2,...,an}
and
{b1,b2,...,bn}
. Both sequences are permutation of
{1,2,...,n}
. You are going to find another permutation
{p1,p2,...,pn}
such that the length of LCS (longest common subsequence) of
{ap1,ap2,...,apn}
and
{bp1,bp2,...,bpn}
is maximum.
Input
There are multiple test cases. The first line of input contains an integer
T
, indicating the number of test cases. For each test case:
The first line contains an integer n(1≤n≤105) - the length of the permutation. The second line contains n integers a1,a2,...,an . The third line contains n integers b1,b2,...,bn .
The sum of n in the test cases will not exceed 2×106 .
The first line contains an integer n(1≤n≤105) - the length of the permutation. The second line contains n integers a1,a2,...,an . The third line contains n integers b1,b2,...,bn .
The sum of n in the test cases will not exceed 2×106 .
Output
For each test case, output the maximum length of 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
Source
你有两个序列{a1,a2,...,an}和{b1,b2,...,bn}. 他们都是1到n的一个排列. 你需要找到另一个排列{p1,p2,...,pn}, 使得序列{ap1,ap2,...,apn}和{bp1,bp2,...,bpn}的最长公共子序列的长度最大.#include <map> #include <set> #include <stack> #include <queue> #include <cmath> #include <ctime> #include <vector> #include <cstdio> #include <cctype> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> using namespace std; #define INF 9223372036854775807 #define inf -0x3f3f3f3f #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define mem0(a) memset(a,0,sizeof(a)) #define mem1(a) memset(a,-1,sizeof(a)) #define mem(a, b) memset(a, b, sizeof(a)) typedef long long ll; int a[100101],b[100101],flag[100101],pos[100101]; int main(){ int t; int n; scanf("%d",&t); while(t--){ scanf("%d",&n); mem0(flag); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); pos[a[i]]=i; } int cnt=0; for(int i=1;i<=n;i++){ scanf("%d",&b[i]); if(a[i]==b[i]){ cnt++; flag[a[i]]=1; } } for(int i=1;i<=n;i++){ if(flag[i]==0){ int p=i; int flag1=0; while(flag[p]==0){ flag[p]=1; int pos1=pos[p]; //对应哪个位置 p=b[pos1]; if(flag1==1) cnt++; flag1=1; } } } printf("%d\n",cnt); } return 0; }