hdu5495

LCS

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 638    Accepted Submission(s): 352


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 nintegers 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
 
参考链接:
官方题解

究竟怎么证明呢?
链接:http://blog.csdn.net/beihai2013/article/details/48884079
感谢beihai2013的回答:假设大于的话,那么至少有一个环对答案的贡献是环里点的个数。然后你就发现它不是环了
已ac的代码:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define N 100010

int a[N],b[N];
int ca[N];
bool mark[N];

int dfs(int now){
    int sum=0;

    while(!mark[now]){
        mark[now]=true;
        sum++;
        now=b[ca[now]];
    }

    return sum;
}

int main(){
    int t;
    int n;

    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            ca[a[i]]=i;
        }
        for(int i=1;i<=n;i++){
            scanf("%d",&b[i]);
        }

        int ans=n;

        memset(mark,false,sizeof(mark));
        for(int i=1;i<=n;i++){
            if(!mark[i]){
                if(dfs(i)>1){
                    ans--;
                }
            }
        }

        printf("%d\n",ans);
    }
}


posted @ 2015-10-24 19:16  buzhidaohahaha  阅读(147)  评论(0编辑  收藏  举报