![]() |
VOOZH | about |
Consider a 2-D map with a horizontal river passing through its center. There are n cities on the southern bank with x-coordinates a(1) β¦ a(n) and n cities on the northern bank with x-coordinates b(1) β¦ b(n). You want to connect as many north-south pairs of cities as possible with bridges such that no two bridges cross. When connecting cities, you can only connect city a(i) on the northern bank to city b(i) on the southern bank. Maximum number of bridges that can be built to connect north-south pairs with the above mentioned constraints.
The values in the upper bank can be considered as the northern x-coordinates of the cities and the values in the bottom bank can be considered as the corresponding southern x-coordinates of the cities to which the northern x-coordinate city can be connected.
Examples:
Input : 6 4 2 1 2 3 6 5 Output : Maximum number of bridges = 2 Explanation: Let the north-south x-coordinates be written in increasing order. 1 2 3 4 5 6 \ \ \ \ For the north-south pairs \ \ (2, 6) and (1, 5) \ \ the bridges can be built. \ \ We can consider other pairs also, \ \ but then only one bridge can be built \ \ because more than one bridge built will \ \ then cross each other. \ \ 1 2 3 4 5 6 Input : 8 1 4 3 5 2 6 7 1 2 3 4 5 6 7 8 Output : Maximum number of bridges = 5
Approach: It is a variation of LIS problem. The following are the steps to solve the problem.
We can also sort on the basis of north x-coordinates and find the LIS on the south x-coordinates.
Maximum number of bridges = 2
Time Complexity: O(n2)
Auxiliary Space: O(n)
Approach - 2 (Optimization in LIS )
Note - This is the variation/Application of Longest Increasing Subsequence (LIS).
Step -1 Initially let the one side be north of the bridge and other side be south of the bridge.
Step -2 Let we take north side and sort the element with respect to their position.
Step -3 As per north side is sorted therefore it is increasing and if we apply LIS on south side then we will able to get the non-overlapping bridges.
Note - Longest Increasing subsequence can be done in O(NlogN) using Patience sort.
The main optimization lies in the fact that smallest element have higher chance of contributing in LIS.
Input: 6 4 2 1
2 3 6 5
Step 1 βSort the input at north position of bridge.
1 2 4 6
5 6 3 2
Step -2 Apply LIS on South bank that is 5 6 3 2
In optimization of LIS if we find an element which is smaller than current element then we Replace the halt the current flow and start with the new smaller element. If we find larger element than current element we increment the answer.
5------------- >6 (Answer =2) HALT we find 3 which is smaller than 6
3 (Answer = 1) HALT we find 2 which is smaller than 3
2 (Answer=1)
FINAL ANSWER = 2
2
Time Complexity - O(NlogN)
Auxiliary Space - O(N)
Problem References:
https://www.geeksforgeeks.org/dsa/variations-of-lis-dp-21/
Solution References:
https://www.youtube.com/watch?v=w6tSmS86C4w