LIS&&LCS

LCS:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#define INF 0x3f3f3f3f
using namespace std;
int main()
{
    char str1[55];
    char str2[55];
    scanf("%s %s",str1+1,str2+1);
    str1[0]=str2[0]='0';
    int len1=strlen(str1)-1;
    int len2=strlen(str2)-1;
    int dp[55][55]={0};
    int i,j;
    for(i=1;i<=len1;i++)
    {
        for(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]);
            }
        }
    }
    stack<char>stk;
    int pos1=len1,pos2=len2;
    while(pos1>0&&pos2>0)
    {
        if(str1[pos1]==str2[pos2])
        {
            stk.push(str1[pos1]);
            pos1--;
            pos2--;
        }
        else
        {
            if(dp[pos1-1][pos2]>dp[pos1][pos2-1])
                pos1--;
            else
                pos2--;
        }   
    }
    while(!stk.empty())
    {
        printf("%c%c",stk.top(),(stk.size()==1)?'\n':' ');
        stk.pop();
    }
    printf("%d\n",dp[len1][len2]);

    return 0;
}

LIS:o(n^2)

#include<cstdio>
#include<algorithm>
using namespace std;
int a[100000];
int dp[100000];
int main()
{

    int l;
    scanf("%d",&l);
    for(int k=0;k<l;k++)
    {
        int n;
        scanf("%d",&n);
        int ans=0;
        for(int i=0;i<n;i++)
        scanf("%d",&a[i]);
        for(int i=0;i<n;i++)
        {
            dp[i]=1;
            for(int j=0;j<i;j++)
            {
                if(a[i]>a[j])
                dp[i]=max(dp[i],dp[j]+1);
            }
            ans=max(ans,dp[i]);
        }
        printf("%d\n",ans);
    }
    return 0;
}

LCS:o(nlogn)

#include <cstdio>  
#include <algorithm>  
#define INF 0x3f3f3f  
using namespace std;  
int dp[50010],a[50010];  
int main()  
{  
    int n,i,j;
    int t;
    scanf("%d",&t);  
    while(t--)  
    {  
        scanf("%d",&n);
        for(i=0;i<n;++i)  
        {  
            scanf("%d",&a[i]);  
            dp[i]=INF;  //初始化数组为无穷大
        }  
        for(i=0;i<n;++i)  
            *lower_bound(dp,dp+n,a[i])=a[i];  //挑选首个大于等于a[i]的数并用a[i]替换
        printf("%d\n",lower_bound(dp,dp+n,INF)-dp);   
    }  
    return 0;  
}   
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值