P1439 [template] the longest common subsequence (LCS)

First look at the ordinary longest common subsequence

Given string A and B, they find the longest common subsequence

DP practice:

Length set f [i] [j] indicates A [1 ~ i] and B [1 ~ j] of the longest common subsequence

那么f[i][j]=max(f[i-1][j],f[i][j-1])

On the basis of the above, if the A [i] = B [j], is f [i] [j] = max (f [i] [j], f [i-1] [j-1] +1)

Code:

 for(int i=1;i<=n;i++)
     for(int j=1;j<=m;j++)
      {
        dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
        if(a1[i]==a2[j])
        dp[i][j]=max(dp[i][j],dp[i-1][j-1]+1);
      }

Complexity is O (mn)


 

So this question because the data 1e5, either time or space will explode, we need to consider another approach

We observe this feature question, A and B are found full array 1 ~ n, that the elements A and B are the same, considering full advantage of this feature.

Because the longest common subsequence is rearwardly bit alignment, the position of an element in a sequence b, if the sequence is incremented, it shows the number b of the overall number of positions in a partial rear

Guess you like

Origin www.cnblogs.com/lcezych/p/11126816.html