Problem:
@ Chen liren
There are n pairs of magpie. Each pair can be expressed as (x, y), X and Y are magpie numbers, and any pair of X is always less than Y. (C, d) can be connected after (a, B), and only when B <C. When many pairs of magpie are connected together, the Magpie Bridge is built. Given n pairs of magpie, please build the longest Magpie Bridge to help meet lovers.
PS: here, the length of Magpie Bridge is the number of magpies that can be connected together.
Analysis I:
In two dimensionsYou can construct a topology graph (Directed Graph) with a side length of 1 and find the longest path.
Time complexity O (N ^ 2 ).
Analysis II:
In one dimensionFirst, sort magpie by X, and use length [I] to represent the I ~ N is a magpie, and the longest length can be set. So:
Length [I] = max {length [I + 1], 1 + length [J]},
Here, J is for satisfying j> I, V [J]. x> V [I]. the minimum subscript of Y, that is, j = min {k | K> I, V [K]. x> V [I]. y }. J can be determined in log (n) time using the binary method.
Time complexity O (nlogn ). Space complexity O (n ).
Code:
Struct magpie {int X, Y ;}; int getpiebridgelength (vector <magpie> & V) {If (v. empty () return 0; STD: Sort (v. begin (), V. end (), [] (const magpie & M1, const magpie & m2) {return m1.x <m2.x ;}); vector <int> Len (v. size (), 0); For (INT I = Len. size ()-1; I> = 0; -- I) {auto it = STD: upper_bound (v. begin () + I, V. end (), V [I]. y, [] (int A, const magpie & M) {return a <m. x;}); Len [I] = STD: max (IT = v. end ()? 1: 1 + Len [it-V. Begin ()], I + 1> = Len. Size ()? 0: Len [I + 1]);} return Len [0];}
Test code:
Int main () {magpie arr [] = {1, 3}, {7, 10}, {4, 5}, {2, 4}; vector <magpie> V (begin (ARR ), end (ARR); cout <getpiebridgelength (v) <Endl; return 0 ;}