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

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 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) 


题意:有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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值