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
 
你有两个序列\{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 <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;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值