洛谷P2543

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

就是一道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;
}

猜你喜欢

转载自www.cnblogs.com/xzx-1228/p/10902583.html
今日推荐