欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

P1439 【模板】最长公共子序列

程序员文章站 2022-06-15 09:29:51
P1439 【模板】最长公共子序列这个题目我是没想到反正我感觉十分的神奇先写一下我在洛谷题解区看见的一个很好理解的题解对于样例 3 2 1 4 51 2 3 4 5我们可以把第一个数组编号位a b c d e。。那么第二个数组就变成了c b a d e现在对于第二个数组的最长上升子序列就是答案,因为首先每个数只出现一次,其次相对于abcde来说其就是一直上升的,所以对于第二个数组来说其上升的序列必然是第一个的子序列,所以说答案就是最长上升子序列。代码如下#include

P1439 【模板】最长公共子序列
这个题目我是没想到反正我感觉十分的神奇先写一下我在洛谷题解区看见的一个很好理解的题解

对于样例 3 2 1 4 5
1 2 3 4 5
我们可以把第一个数组编号位a b c d e
。。那么第二个数组就变成了c b a d e
现在对于第二个数组的最长上升子序列就是答案,因为首先每个数只出现一次,其次相对于abcde来说其就是一直上升的,所以对于第二个数组来说其上升的序列必然是第一个的子序列,所以说答案就是最长上升子序列。
代码如下

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<string>
#include<vector>
#include<queue>
#include<algorithm>
#include<deque>
#include<map>
#include<stdlib.h>
#include<set>
#include<iomanip>
#include<stack>
#define ll long long
#define ms(a,b) memset(a,b,sizeof(a))
#define lowbit(x) x & -x
#define fi first
#define ull unsigned long long
#define se second
#define lson (rt<<1)
#define rson (rt<<1|1)
#define endl "\n"
#define bug cout<<"----acac----"<<endl
#define IOS ios::sync_with_stdio(false), cin.tie(0),cout.tie(0)
using namespace std;
const int maxn = 1e5+10;
const int maxm = 1.5e5 + 50;
const double eps = 1e-10;
const double inf = 0x3f3f3f3f;
const ll  lnf = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e4 + 7;
const  double pi = 3.141592653589;
struct node
{
	int a, b;
}e[maxn];
bool cmp(node A, node B)
{
	return A.a < B.a;
}
int dp[maxn];
map<int, int>p;
int main()
{
	int n;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &e[i].a);
		p[e[i].a] = i;
	}
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &e[i].b);
		e[i].b = p[e[i].b];
	}
	//sort(e + 1, e + 1 + n, cmp);
	int cnt = 0;
	for (int i = 1; i <= n; i++)//求上升子序列
	{
		if (e[i].b > dp[cnt])
		{
			dp[++cnt] = e[i].b;
		}
		else
		{
			int pos = lower_bound(dp + 1, dp + 1 + cnt, e[i].b) - dp;
			dp[pos] = e[i].b;
		}
	}
	printf("%d\n", cnt);
	return 0;
}

本文地址:https://blog.csdn.net/qcccc_/article/details/108835470

相关标签: dp