51NOD 1376 最长递增子序列的数量 [CDQ分治]

题意:求最长上升子序列的数量

思路1:从左向右扫一遍,并实时更新权值线段树( nlogn )

思路2:cdq分治,注意不能 归并排序,因为左侧有序的时候,右侧还未有序。( nlogn^2 )

#include 
#include 
using namespace std;
const int maxn = 50005;
typedef long long LL;
const LL mod = 1000000007;
LL cnt[maxn];
int ans[maxn],c[maxn],a[maxn];
LL ad( int x,int y ){
    x  += y;
    return x%mod;
}
bool cmp( int x,int y ){
    return a[x] == a[y] ? x>y: a[x] < a[y] ;
}
void cdq( int l,int r ){
    if( l >= r ) return;
    int mid = l+r>>1;
    cdq( l,mid );
    int tot = 0;
    for( int i = l;i <= r;i++ ) c[tot++] = i;
    sort( c,c+tot,cmp );
    int mx=0;LL cc=0;
    for( int i = 0;i < tot;i++ ){
        int x = c[i];
        if( x > mid ){
                if( mx+1 > ans[x] ){
                    ans[x] = mx+1; cnt[x] = cc;
                }else if( mx+1==ans[x] ){
                    cnt[x] = ad(cnt[x],cc);
                }
        }else{
            if( ans[x]>mx ){
                mx = ans[x];cc = cnt[x];
            }else if( ans[x]==mx ){
                cc = ad(cc,cnt[x]);
            }
        }
    }
    cdq( mid+1,r );
}
int main(){
    int n;
    scanf("%d",&n);
    for( int i = 1;i <= n;i++ ){
        scanf("%d",&a[i]);ans[i] = cnt[i] = 1;
    }
    cdq( 1,n );
    int mx = 0;
    for( int i = 1;i <= n;i++ )mx = max( mx,ans[i] );
    LL res = 0;
    for( int i = 1;i <= n;i++ ){
        if( ans[i]==mx ){
            res = ad(res,cnt[i]);
        }
    }
    printf("%d\n",res);
    return 0;
}

 

你可能感兴趣的:(cdq分治)