Magpie Bridge Length

Source: Internet
Author: User


@ 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 ).


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 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.