forked from mazedrupok/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 9
/
LIS with nlogn.cpp
58 lines (56 loc) · 1.42 KB
/
LIS with nlogn.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
using namespace std;
int bsearch(int a[], int i, int j, int key) {
int mid = (i+j)/2;
if(j < i)
return j;
else
if(a[mid] > key)
return bsearch(a, i, mid-1, key);
else
return bsearch(a, mid+1, j, key);
}
int LIS_n2(int a[], int size) {
int i, j, len[size];
for(i = 0; i < size; i++) len[i] = 1;
for(i = 1; i < size; i++) {
for(j = 0; j < i; j++) {
if(a[i] > a[j] && len[i] < len[j]+1)
len[i] = len[j] + 1;
}
}
return len[size-1];
}
int LIS_nlogn(int a[], int size) {
int s[size];
int i;
int j = -1;
int p, k;
for(i = 0; i <= size; i++) s[i] = 0;
for(i = 0; i <= size; i++) {
if(j == -1) s[++j] = a[i];
else {
if(s[j] < a[i]) s[++j] = a[i];
else {
p = bsearch (s, 0, j, a[i]);
s[p+1] = a[i];
}
}
}
cout << "O(nlogn) algorithm subsequence: \n";
for (i = 0; i <= j; i++) cout << s[i] << " ";
cout << "\n";
return j+1;
}
int main()
{
int a[]={10, 22, 9, 33, 21, 50, 41, 60, 80};
int size = sizeof(a)/sizeof(a[0]);
cout << "O(n^2) algorithm subsequence length: " << LIS_n2(a, size) << "\n";
cout << "Subsquence length: " << LIS_nlogn(a, size-1) << "\n";
}
/*
output {9, 21, 33, 41, 60, 80}
21 should be after 33.. that is a mistake of this code..
collected from rabiul :(
*/