-
Notifications
You must be signed in to change notification settings - Fork 0
/
LIS_O(N log K).cpp
146 lines (106 loc) · 2.08 KB
/
LIS_O(N log K).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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// LIS -- O(N log K)
#include<bits/stdc++.h>
using namespace std;
const int inf=9999;
int seq[100], I[100] , ilen=0 , n , L[100] , lisseq[100];
int search_binary(int lo, int hi, int itm)
{
int mid;
while(lo <= hi)
{
mid = (lo + hi) / 2;
if(I[mid] < itm)
{
lo = mid + 1;
}
else
{
hi = mid - 1;
}
// if(I[mid] == itm)
// {
// return mid;
// }
//
// else if(I[mid] > itm)
// {
// hi = mid-1;
// }
//
// else if(I[mid] < itm)
// {
// lo = mid+1;
// }
}
return lo;
}
int LIS()
{
int i , r , lislength=0 , pre=0, now=0;
for(i=0;i<n;i++)
{
r = search_binary(0, lislength, seq[i]);
I[r] = seq[i];
L[i] = r;
if(lislength < r)
{
lislength = r;
}
}
//cout << "LIS length = " << lislength << "\n";
return lislength;
}
void find_sequence(int mxlen)
{
int i=0 , j ;
//for(i=0;i<n;i++)cout << L[i] << " ";
for(j=1; j<n; j++)
{
if(L[j] > L[i])
{
i = j;
}
}
//cout << "i = " << i;
int top = L[i] - 1;
lisseq[top] = seq[i];
top--;
for(j=i-1; j>=0; j--)
{
if(seq[j] < seq[i] and L[j] == L[i] - 1)
{
i = j;
lisseq[top] = seq[i];
top--;
}
}
cout << "LIS Sequence: ";
for(i=0;i<mxlen;i++)
{
cout << lisseq[i] << " ";
}
}
int main()
{
int i;
//lislength=0;
//memset(I, inf, sizeof(I));
memset(L, 1, sizeof(L));
I[ilen++] = -inf;
//freopen("input.txt" , "r" , stdin);
//for(i=0;i<11;i++) cout << I[i] << " ";
while(cin >> n)
{
for(i=0;i<n;i++)
{
cin >> seq[i];
I[ilen++] = seq[i];
}
//for(i=0;i<11;i++) cout << I[i] << " ";
int len = LIS();
cout << "LIS length = " << len << "\n";
find_sequence(len);
cout << "\n";
}
return 0;
}