天天看點

【bellovin】LIS+dp

Peter has a sequence a1,a2,…,ana1,a2,…,an and he define a function on the sequence – F(a1,a2,…,an)=(f1,f2,…,fn)F(a1,a2,…,an)=(f1,f2,…,fn), where fifi is the length of the longest increasing subsequence ending with aiai.

Peter would like to find another sequence b1,b2,…,bnb1,b2,…,bn in such a manner that F(a1,a2,…,an)F(a1,a2,…,an) equals to F(b1,b2,…,bn)F(b1,b2,…,bn). Among all the possible sequences consisting of only positive integers, Peter wants the lexicographically smallest one.

The sequence a1,a2,…,ana1,a2,…,an is lexicographically smaller than sequence b1,b2,…,bnb1,b2,…,bn, if there is such number ii from 11 to nn, that ak=bkak=bk for 1≤k

#include<cstdio>
#include<cstring> 
#define INF 0x3f3f3f3f
#include<algorithm>
using namespace std;
int g[],a[],dp[];
int T,n;
int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        fill(g+,g+n+,INF);
        memset(dp,,sizeof(dp));
        for(int i=;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        for(int i=;i<=n;i++)
        {
            int pos=lower_bound(g+,g+n+,a[i])-g;//找出第一個大于等于a[i]的位置 
            g[pos]=min(g[pos],a[i]);//g[]為INF,若a[i]小就把a[i]放進去 
            dp[i]=max(pos,dp[i]);//dp[]是從1遞增的一次加1; 
        }
        /*
        g[]指派為INF,肯定能找到 大于等于a[i]的值,
        此時g[pos]這個位置的值就換成a[i],下一次再找,
        就會先與放進去的值比較,
        若剛剛放進去的值大,那麼現在的值又會取代它放到這個位置,
        這就說明此時以這個值為結尾的序列長度為1,pos的值不會改變;
        若剛剛放進去的值小,就說明能夠構成長度大于1 的上升子序列 ,
        pos的值會依次增大,每次都是加1 
        同時dp[i]裡的值會取max(pos,dp[i]),再下一次,依次找,
        到最後dp[n]裡面存的值就是最長子序列的長度;
        每一個dp[i]就是以a[i]為結尾的最長子序列的長度; */ 
        for(int i=;i<=n;i++)
        {
            printf("%d%c",dp[i],i==n?'\n':' ');
        }
    }

    return ;
}