hdu5495LCS(好题)

LCS

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
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(1n105) - 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
BestCoder Round #58 (div.2)
 
你有两个序列\{a_1,a_2,...,a_n\}{a1,a2,...,an}\{b_1,b_2,...,b_n\}{b1,b2,...,bn}. 他们都是11nn的一个排列. 
你需要找到另一个排列\{p_1,p_2,...,p_n\}{p1,p2,...,pn}, 使得序列\{a_{p_1},a_{p_2},...,a_{p_n}\}{ap1,ap2,...,apn}\{b_{p_1},b_{p_2},...,b_{p_n}\}{bp1,bp2,...,bpn}的最长公共子序列的长度最大.
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
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;
}



你可能感兴趣的:(hdu)