最長上公升子串行與最長下降子串行logn 最優解列印

2022-06-13 03:21:11 字數 2307 閱讀 4581

emmm...還是看的題解,還不是很懂,但是**還挺簡單的,先記下來

2021/3/14更:

今天實驗室大佬講了一下最長遞增子串行logn求法同時求出最優解(如果存在多個長度相同,則字典序最小),聽說是去年藍橋盃國賽的題,

先說明一下變數,val陣列存的基礎變數,pre陣列是logn求法必要的那個陣列,len是最長遞增子串行長度,pos表示在pre陣列中的每個數在val陣列中的位置

大佬題解的fa表示該點如果存在結果序列中,則fa標記的點也必定在結果序列中,我的fa表示pre陣列中某個數的上乙個數在val陣列中的位置,結果陣列res

可能有點繞,結合描述和**看看吧

大佬給出的題解是:

在二分查詢出要插入位置p之後,p之前位置的數的相對位置一定是比當前位置要小同時數值也更小,假如後乙個數出了,前乙個數也必定要出,用fa標記起來

如果前面的數被替換掉,替換的那個數的相對位置一定是比當前數要大的,所以與當前數是無關的,,然後標記fa[0]=-1為終止點,就能從fa[len]到fa[0]列印出結果路徑了

我的思路:

我原本是聽大佬講完了這道題,以為自己寫的就是大佬跟咱們說的,所以才會有fa但是意義不一樣=-=,但是這都不重要了...

求出pre陣列後,我們可以知道的是,pre陣列的最後一位一定是在最終解res陣列中的最後一位的,自己可以想象理解一哈,

然後我們就可以從後往前選,如果相對位置大於res陣列後乙個位置的數在val陣列中的相對位置,則找上乙個放在這裡的數,看相對位置得行不,得行就取他

而我們替換的原則又是小的替換大的(在最長遞增子串行中),所以只要取到乙個相對位置滿足條件的,它的值一定是比這個位置它上一次替換掉的數小的,

所以字典序就是最小的了,這樣咱們就能得到乙個res陣列啦,比大佬的程式稍微慢一點,但量級是相同的...

由於沒有測試題可以實驗,可能會有錯,歡迎指出

大佬的簡介**:

#include #include 

#include

#include

#include

#include

#include

using

namespace

std;

const

int maxn=1e5+100

;int

a[maxn];

intlen,n;

inttmp[maxn];

intfa[maxn],pos[maxn];

void print(int

x)int

main()

print(pos[len]);

return0;

} /*

865 158 170 299 300 155 207 389

*/

我的**:

#include#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

using

namespace

std;

typedef

long

long

ll;inline

intread()

const

int maxn = 100005

;int

val[maxn];

intpre[maxn];

intfa[maxn];

intpos[maxn];

intlen,n;

intmain()

len = 0

; pre[

0] =0

;

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

else

}cout

<< len

res(len + 1, 0

);

int lastpos = pos[len];//

pre陣列中的最後乙個數一定res陣列的最後乙個,找到最後乙個數的位置

//然後從後往前找

for (int i = len - 1; i >= 1; i--)

res[i] =val[now];

lastpos =now;

}res[len] =val[pos[len]];

for (int i = 1; i <= len; i++)

return0;

}

最長上公升子串行,最長不下降子串行

最長上公升子串行 include includeusing namespace std const int n 23333 12 int dp n a n int n int binarysearch int k,int len else if k dp mid else mid l r 1 ret...

最長上公升子串行 和 最長不下降子串行

最長上公升子串行 是嚴格上公升的,alower bound 返回序列中大於等於key值的第乙個數 比如說序列 1 2 3 4 5,key值為3,使用lower bound返回第三個數 最長不下降子串行 不是嚴格上公升,可以存在多個數相等的情況,用upper bound upper bound 返回序...

最長上公升 不下降子串行

最長上公升 不下降子串行 lis 有兩種方法 1.動態規劃,o n 2 容易得出o n 2 的dp遞推公式 d i max 1 1 j d i 為以元素i結尾的最長子序列個數。這樣經過兩重迴圈一次遍歷可以得到最長上公升子串行。view code 1 include 2 include 3 inclu...