题意:
求一个置换,使得置换后的两个序列的LCS最大,求这个最大LCS
分析:
我们手算可以发现第一序列对于第二个序列的置换,可以把序列分成若干个循环节环,显然环与环之间是独立的.
事实上对于一个长度为l(l>1)的环,我们总可以得到一个长度为l−1的LCS
那么答案就是ans=∑max{1,l−1}
记得先排序−−求循环节是从1−n
代码:
//
// Created by TaoSama on 2015-10-03
// Copyright (c) 2015 TaoSama. All rights reserved.
//
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;
int n, a[N], b[N];
bool vis[N];
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
// freopen("out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
int t; scanf("%d", &t);
while(t--) {
scanf("%d", &n);
for(int i = 1; i <= n; ++i) scanf("%d", a + i);
for(int i = 1; i <= n; ++i) {
int x; scanf("%d", &x);
b[a[i]] = x;
}
memset(vis, false, sizeof vis);
int ans = 0;
for(int i = 1; i <= n; ++i) {
if(!vis[i]) {
int j = i, cnt = 0;
while(!vis[j]) {
++cnt;
vis[j] = true;
j = b[j];
}
ans += max(1, cnt - 1);
}
}
printf("%d\n", ans);
}
return 0;
}
本文探讨了如何通过置换两个序列来获得最长公共子序列(LCS)的最大值,并提出了一种有效的算法。该算法首先将序列划分为多个循环节环,然后通过计算每个循环节环的长度来确定LCS的最大值。
&spm=1001.2101.3001.5002&articleId=48883627&d=1&t=3&u=d80fa2ca047c4908919aa85462ed6ebe)
660

被折叠的 条评论
为什么被折叠?



