DP ---- LIS (rising up sequence), and the LCS (the longest common subsequence) issues

LIS problem

https://www.acwing.com/problem/content/898/

Ideas: First, an array of numbers (the original number) a in the deposit input opening up an array of f to keep a result, the final length is the final answer array of f; if the array f now saved number, when to array a first i when a position first determined a [i]> f [cnt ]? If greater than this number is added directly to the array f, i.e. f [++ cnt] = a [ i]; apparent during this operation.
When the number of a [i] <f when [CNT] = a, we have to replace with a [i] f the first array is not less than a [i], because the whole process is that we maintain the array f an incremental array, we can use a binary search to find the corresponding position directly under logn time complex situation, and then replace, i.e. f [l] = a [i ].

Meaning we use a [i] to replace f [i] is: the a [i] is the last strictly monotonic increasing sequence number, the sequence number is this number in a l.

So that when we go through a complete array after you can get the final result.

Analysis time complexity: O (nlogn) O (nlogn)
C ++ Code

 

#include<bits/stdc++.h>
using namespace std;
int n,a[100001],dp[100001],len;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    dp[1]=a[1],len=1;
    for(int i=2;i<=n;i++){
        if(dp[len]<a[i]) dp[++len]=a[i];

        else{
            int j=lower_bound(dp+1,dp+len+1,a[i])-dp;//lower bound真好用
            dp[j]=a[i];

        }
    }
    cout<<len;
    return 0;
} 

LCS problem

 Quite simply, nothing to say, look at the code should be able to understand.

C ++ code

 

#include<bits/stdc++.h>
using namespace std;
string a,b;
int dp[2001][2001];
int main(){

    int len1,len2;
    cin>>len1>>len2>>a>>b;
    for(int j=1;j<=len2;j++)
    for(int i=1;i<=len1;i++){
    if(a[i-1]==b[j-1]) dp[i][j]=max(dp[i][j],dp[i-1][j-1]+1);
    else dp[i][j]=max(dp[i][j-1],dp[i-1][j]);//阶段划分:已经处理的前缀长度 
    }
    cout<<dp[len1][len2];
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/myhnb/p/11305551.html