Longest chain of pairs

后端 未结 5 640
面向向阳花
面向向阳花 2021-02-04 10:16

You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. A pair (c,d) can follow

5条回答
  •  离开以前
    2021-02-04 11:01

    First, this problem can be viewed as plotting points on a two dimensional grid where x co-ordinate of each point is less than y co-ordinate of that point. Now you're asked to find the longest chain such that every i+1 th point is both above and to the right of the ith point (and the y co-ordinate of the ith point is less than x co-ordinate of i+1th point).

    now let's sort the points first based on their x co-ordinate. Then we start visiting the sorted points from lowest x co-ordinate, if there's a tie for x co-ordinate then we'll visit points with higher y co-ordinate first. now for an example if we're working on the ith point, we know that all points already visited have lower or similar x co-ordinate of the ith one. So the longest chain end at point i will be the longest chain that we've already got with y co-ordinate<=x co-ordinate of the current point.

    We can do it efficiently with an efficient data structure like segment tree or Binary indexed tree.

    Runtime of this solution is : O(NlgN) where N is the number of points (pairs in the given problem).

提交回复
热议问题