首先介绍一下什么是最长上升子序列
举一个例子 2 1 5 3 6 4 8 9 最长上身子序列是 1 3 4 8 9(不连续)
#include <iostream>
#include <algorithm>
using namespace std;
int a[1001],ans[1001],len;
int main()
{
int n,T;
cin>>T;
while(T--)
{
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
ans[1]=a[1];
len=1;
for(int i=2;i<=n;i++)
{
if(a[i]>ans[len])
ans[++len]=a[i];
else
{
int pos=lower_bound(ans,ans+len,a[i])-ans;
ans[pos]=a[i];
}
}
cout<<len<<endl;
}
return 0;
}
LCS 最长公共子序列
例如:
对序列 1,3,5,4,2,6,8,7和序列 1,4,8,6,7,5 来说
序列1,8,7是它们的一个公共子序列。
请注意: 空序列是任何两个序列的公共子序列。
例如: 序列1,2,3和序列4,5,6的公共子序列只有空序列。
<1>动态规划
eg:
abcfbc abfcab
programming contest
abcd mnp
Output
4
2
0
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
ll dp[1001][1001];
char str1[1111],str2[1111];
int main()
{
while(~scanf("%s%s",str1+1,str2+1))
{
str1[0]='.';
str2[0]='.';
ll len1=strlen(str1);
ll len2=strlen(str2);
memset(dp,0,sizeof(dp));
for(ll i=1; i<len1; i++)
{
for(ll j=1; j<len2; j++)
{
if(str1[i]==str2[j])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
printf("%lld\n",dp[len1-1][len2-1]);
}
return 0;
}