HDU-5495 LCS(最长公共子序列)

来源:互联网 发布:时序数据库应用场景 编辑:程序博客网 时间:2024/05/17 22:20

LCS

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


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 integerT, 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
231 2 33 2 161 5 3 2 6 43 6 2 4 5 1
 

Sample Output
24
 

Source

BestCoder Round #58 (div.2) 


题意:有2个序列A,B,里面的元素都是从1~n,要求同时排序A,B的元素,使得2个序列的公共子序列最长,求出最长的公共子序列
(注意:如果A中第i个元素移动到位置j,那么B重第i个元素也要移动到位置j)
题解:易知,A,B相应位置上的元素有2种情况:相同或不相同.相同时就不用考虑,直接算入公共子序列的长度即可;不相同时,我们可以知道,总可以排序使得他们构成一个环,
      1  3  2  4
例如: 3  2  4  1,我们总能构成一个这样的环,那么这个环的公共子序列长度就是3,即如果一个环的长度为n,那么他的公共子序列长度为n-1,因此只要把所有环的个数找出来
用总长度减去环的个数就是所求答案.

#include<cstdio>#include<algorithm>#include<queue>#include<vector>#include<string.h>#include<functional>using namespace std;typedef long long LL;const int maxn = 1e5 + 5;int a[maxn],p[maxn],vis[maxn];int main(){    int T,n;  //  freopen("in.txt","r",stdin);    scanf("%d",&T);    while(T--){        scanf("%d",&n);        memset(vis,0,sizeof(vis));        for(int i=1;i<=n;i++) p[i]=i;        for(int i=1;i<=n;i++) {            int x;scanf("%d",&x);            a[x]=i;         //x出现在第i个位置        }        for(int i=1;i<=n;i++) {            int x;scanf("%d",&x);            p[i]=a[x];     //第二个序列中的x对应的第一个序列的x的位置(2个x间连一条边)        }        int cnt=0;        for(int i=1;i<=n;i++) {            if(p[i]!=i&&!vis[i]) {    //2个序列中第i个数不相等并且未被标记的情况                vis[i]=1;                int k=p[i];                while(!vis[k]){    //如果所有相连的边是一个环且个数为n,则他们的公共子序列等于n-1                    vis[k]=1;                    k=p[k];                }                cnt++;            }        }        printf("%d\n",n-cnt);    }    return 0;}


1 0
原创粉丝点击