首页 技术 正文
技术 2022年11月23日
0 收藏 623 点赞 2,505 浏览 1867 个字

Problem Description

You are given two sequence {a1,a2,...,an} and {b1,b2,...,bn}. Both sequences are permutation of {,,...,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(≤n≤) - 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 ×.

 Output

For each test case, output the maximum length of LCS.

Sample Input


 Sample Output


 SourceBestCoder Round #58 (div.2) 

题意:

给出1~n的两个排序a[n],b[n],求用某个排序p[n],使得a[p[0]],a[p[1]],a[p[2]]······与b[p[0]],b[p[1]],b[p[2]]······的最长公共子序列取得最大值,求最终取得的LCS多大。

思路:

LCS一定会tle的,关键就是这是1~n的序列,所以必然a[],b[]存在相同的数字,也就是一定会由一些循环节组成,而每个循环节经过排列首尾相接一定会有只相错一位的情况,最终的LCS也就是总长减去循环节的个数,特判自环不减就行了。直接深搜写的,跑得比较慢。

来自官方题解:

题目中给出的是两个排列, 于是我们我们可以先把排列分成若干个环, 显然环与环之间是独立的. 事实上对于一个长度为l(l>1)的环, 我们总可以得到一个长度为l−1的LCS, 于是这个题的答案就很明显了, 就是n减去长度大于1的环的数目.

 #pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<bitset>
#include<map>
#include<vector>
#include<stdlib.h>
#include <stack>
using namespace std;
#define PI acos(-1.0)
#define max(a,b) (a) > (b) ? (a) : (b)
#define min(a,b) (a) < (b) ? (a) : (b)
#define ll long long
#define eps 1e-10
#define MOD 1000000007
#define N 100006
#define inf 1e12
int n;
int a[N];
int b[N];
int vis[N];
bool dfs(int x){
int tmp=b[x];
if(!vis[tmp]){
vis[tmp]=;
dfs(a[tmp]);
return true;
}
return false;
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
memset(vis,,sizeof(vis));
scanf("%d",&n);
for(int i=;i<=n;i++){
scanf("%d",&a[i]);
}
int x;
for(int i=;i<=n;i++){
scanf("%d",&x);
b[x]=i;
}
int ans=; for(int i=;i<=n;i++){
if(!vis[i]){
vis[i]=;
if(!dfs(a[i])){
ans--;
}
ans++;
}
}
printf("%d\n",n-ans);
}
return ;
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,993
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,507
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,350
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,135
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,768
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,845