LIS, 一道比較經典的動態規劃題目。
對於長爲n的序列 F[n] = max{F[k] + 1,F[n] | if arr[k] < arr[n] }
時間複雜度 O(N^2) 線性空間。
最近看到網上的一種 nlgn的解法,深受啓發:
思路是這樣的:
令一個數組 pos[x] 來表示上升序列中第i個數字最小是多少。
從 arr[i] ~arr[n] 遍歷一遍,過程如下:
(1) i = 1 pos[1] = arr[i];
(2)如果 arr[i] > pos[cnt] (cnt表示當前標記數量) 則 pos[++cnt] = arr[i] 因爲大,所以往後記一位。
(3)如果上述情況都不滿足,那麼就在 pos[0]~pos[cnt] 中尋找與他最相鄰的兩個位置,把較大者“替換”爲自己。
因爲是個單調數組 ,二分法適合。
綜上所述過程時間複雜度 (NlgN),線性空間。
不過注意的是 pos[1~n] 不一定爲(通常不爲)所求的最長上升序列,他只是表示了第i個元素的最小值,如果需要構造解,則需要從頭遍歷一遍,對於第i個數字,如果滿足
B[now] <= arr[i] < B[now+1] 即可把 arr[i] 作爲上升序列中的第Now個元素。
無論如何,cnt到最後的值確確實實等於序列的長度。
#include <iostream>
#include <fstream>
#define N 600000
using namespace std;
int arr[N];
int B[N];
int cnt = 0;
ifstream fin ("LCSin.txt");
ofstream fout("LCSout.txt");
int b_search(int x)
{
int s = 0 , t = cnt;
while(s < t)
{
int q = (t + s) / 2;
if (B[q] >= x) t = q;
else s = q + 1;
}
return s;
}
int main()
{
int n;
fin >> n;
for (int i = 1 ;i <= n ; ++i)
fin >> arr[i];
B[1] = arr[1];
cnt = 1;
for (int i = 2; i <= n ; ++i)
{
if(arr[i] > B[cnt])
B[++cnt] = arr[i];
else
{
int j = b_search(arr[i]);
B[j] = arr[i];
}
}
fout << cnt << endl;
fin.close();
fout.close();
}