zoukankan      html  css  js  c++  java
  • LCS

    LCS

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


    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
    一个环的问题,根据题意可知,出现环answer += len() - 1;没有环,则answer += len();
    并且若没有环即上下数字相同,即len() = 1;
    简单的搜索一下环就可以了。
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    const int maxn = 1e5+5;
    using namespace std;
    int a[maxn];
    int b[maxn];
    int sum[maxn];
    bool vis[maxn];
    int main(){
        int T;
        scanf("%d",&T);
        while(T--){
            int n;
            scanf("%d",&n);
            for(int i = 1; i <= n; i++){
                scanf("%d",&a[i]);
            }
            for(int i = 1; i <= n; i++){
                scanf("%d",&b[a[i]]);
            }
            for(int i = 1; i <= n; i++){
                vis[i] = 0;
            }
            int ans = 0;
            for(int i = 1; i <= n; i++){
                int x = a[i];
                if(vis[x])continue;
                int cnt = 0;
                while(!vis[x]){
                    vis[x] = 1;
                    x = b[x];
                    cnt++;
                }
                if(cnt == 1)ans++;
                else ans += cnt-1;
            }
            printf("%d
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    12小时制时间
    sqlserver 安装和配置
    建议71:区分异步和多线程应用场景
    AVD管理器提示:PANIC:Could not open:AVD名称 解决办法
    一道看似复杂但是简单的c#面试题
    XML Schema 配置文件自动生成c#类设计案例子
    VS2010中的调试技巧 断点
    文章已被删除
    使用MONO使.net程序脱离.net框架运行
    5个很好用的.net 分析工具
  • 原文地址:https://www.cnblogs.com/ACMessi/p/4854631.html
Copyright © 2011-2022 走看看