Uncrossed Lines in C++


Suppose we have written the integers of A and B (in the order they are given) on two separate horizontal lines. Now, we may draw connecting lines: a straight line connecting two numbers A[i] and B[j] such that −

  • A[i] == B[j];

  • The line we draw that does not intersect any other connecting (non-horizontal) line.

We have to keep in mind that connecting lines cannot intersect even at the endpoints − each number can only belong to one connecting line. Find the maximum number of connecting lines. So if the input is like [1,4,2] and [1,2,4], then the output will be 2.

142
124

We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, this is because the line from A[1]=4 to B[2]=4 will intersect the line from A[2]=2 to B[1]=2.

To solve this, we will follow these steps −

  • Define a method called solve(), this will take, i, j, the array A, array B and the matrix dp

  • if i is out of range of array A, return 0

  • if j is out of range of array B, then return 0

  • nj := j

  • while nj < size of B and B[nj] is not A[i]

    • increase nj by 1

  • temp := 1 when nj < size of B, otherwise 0

  • ret := max of (solve(i + 1, j, A, B, dp) and temp) + solve(i + 1, nj + 1, A, B, dp)

  • dp[i, j] := ret and return ret

  • From the main method

  • n := size of A, m := size of B

  • create a matrix dp of size n x m, and fill this with – 1

  • call solve(0, 0, A, , dp)

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(int i, int j, vector <int>&A, vector <int>&B, vector <
   vector <int> >& dp){
      if(i >= A.size()) return 0;
      if(j >= B.size()) return 0;
      if(dp[i][j] != -1) return dp[i][j];
      int nj = j;
      while(nj < B.size() && B[nj] != A[i]) nj++;
      int ret = max(solve(i + 1, j, A, B, dp), (nj < B.size() ? 1 :
      0) + solve(i + 1, nj + 1, A, B, dp));
      return dp[i][j] = ret;
   }
   int maxUncrossedLines(vector<int>& A, vector<int>& B) {
      int n = A.size();
      int m = B.size();
      vector < vector <int > > dp(n, vector <int>(m, -1));
      return solve(0, 0, A, B, dp);
   }
};
main(){
   vector<int> v1 = {1,4,2};
   vector<int> v2 = {1,2,4};
   Solution ob;
   cout << (ob.maxUncrossedLines(v1, v2));
}

Input

[1,4,2]
[1,2,4]

Output

2

Updated on: 30-Apr-2020

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements