首页 > 其他 > 详细

洛谷P2543

时间:2019-05-21 22:49:33      阅读:111      评论:0      收藏:0      [点我收藏+]

一道跟哈希没有任何关系的题目

就是一道LCS模版题

普通写法

//洛谷P2543
#include<bits/stdc++.h>
#include       <map>
#include       <set>
#include     <ctime>
#include     <cmath>
#include     <queue>
#include     <stack>
#include    <cstdio>
#include    <vector>
#include   <cstring>
#include   <cstdlib>
#include <iostream>
#include<algorithm>
#include<cmath>
#include<stdlib.h>
using namespace std;
int dp[5000][5000];
int main()
{
    string x,y;
    cin>>x>>y;
    int n=x.length();
    int m=y.length();
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(x[i-1]==y[j-1])
                dp[i][j]=dp[i-1][j-1]+1;
            else
            {
                dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
            }
            
        }
    }
    cout<<dp[n][m]<< endl;
}

 这样能过是因为题目数据出水了,没有达到长度为10000的时候,如果长度为10000,则会爆数组

所以我们采用滚动数组:我们发现dp[i][j]只与上一层有关,则可以滚动

滚动代码:

//洛谷P2543
#include<bits/stdc++.h>
#include       <map>
#include       <set>
#include     <ctime>
#include     <cmath>
#include     <queue>
#include     <stack>
#include    <cstdio>
#include    <vector>
#include   <cstring>
#include   <cstdlib>
#include <iostream>
#include<algorithm>
#include<cmath>
#include<stdlib.h>
using namespace std;
int dp[3][10001];
int main()
{
    string x,y;
    cin>>x>>y;
    int n=x.length();
    int m=y.length();
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(x[i-1]==y[j-1])
                dp[i%2][j]=dp[(i-1)%2][j-1]+1;
            else
            {
                dp[i%2][j]=max(dp[(i-1)%2][j],dp[i%2][j-1]);
            }
            
        }
    }
    cout<<dp[n%2][m]<< endl;
}

 

洛谷P2543

原文:https://www.cnblogs.com/xzx-1228/p/10902583.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!