最长上升子序列nlogn解法详解 poj 2533

先上一个n^2的算法:

 1 #include <iostream>

 2 using namespace std;

 3 

 4 const int N = 1000;

 5 int a[N];

 6 int g[N];

 7 

 8 int main ()

 9 {

10     int n;

11     while ( cin >> n )

12     {

13         for ( int i = 0; i < n; i++ ) 

14         {

15             cin >> a[i];

16             g[i] = 1;

17         }

18         int ans = g[0];

19         for ( int i = 1; i < n; i++ )

20         {

21             for ( int j = 0; j < i; j++ )

22             {

23                 if ( a[j] >= a[i] ) continue;

24                 if ( g[j] + 1 > g[i] ) g[i] = g[j] + 1;

25             }

26             if ( g[i] > ans ) ans = g[i];

27         }

28         cout << ans << endl;

29     }

30     return 0;

31 }

然后是nlogn的:

 1 #include <algorithm>

 2 #include <iostream>

 3 using namespace std;

 4 

 5 const int INF = 1 << 29;

 6 const int N = 1000;

 7 int s[N];

 8 int top;

 9 

10 int main ()

11 {

12     int n;

13     while ( cin >> n )

14     {

15         top = 0;

16         s[top++] = INF;

17         for ( int i = 0; i < n; i++ ) 

18         {

19             int tmp;

20             cin >> tmp;

21             if ( tmp > s[top - 1] )

22             {

23                 s[top++] = tmp;

24             }

25             else

26             {

27                 int pos = upper_bound( s, s + top, tmp ) - s;

28                 s[pos] = tmp;

29             }

30         }

31         cout << top << endl;

32     }

33     return 0;

34 }

 

你可能感兴趣的:(poj)