天天看點

Codeforces 597D Subsequences (二維樹狀數組入門+DP優化) 高清重制版

For the given sequence with n different elements find the number of increasing subsequences with k + 1 elements. It is guaranteed that the answer is not greater than 8·1018.

Input

First line contain two integer values n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 10) — the length of sequence and the number of elements in increasing subsequences.

Next n lines contains one integer ai (1 ≤ ai ≤ n) each — elements of sequence. All values ai are different.

Output

Print one integer — the answer to the problem.

Examples

Input

5 2
1
2
3
5
4
      

Output

7      
#pragma comment(linker, "/STACK:102400000,102400000")
#include<bits/stdc++.h>
using namespace std;

#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)

#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define ll long long

const int  maxn =3e5+5;
const int mod=1e9+7;
/*
題目意思很清楚。

在樹狀數組的概念裡,
參有很多貢獻的思維。
這道題中tree[i][j]樹狀數組維護的是,
前i個數中遞增長度小于等于j的數量,
其中遞增的含義是DP值賦予的,
那麼這樣的tree[i][j],是由什麼貢獻而來的呢,
是由dp[i][j]貢獻的,代表以i位置結尾長度為j的數量,
tree[i][j]可以寫成dp的二重求和形式。

首先樹狀數組的操作還是全部都是套路,且是1—base。
下面有個問題,dp數組如何更新,
按正常的dp思維,
dp[i][j]=sigma p:p<i&&a[p]<a[i], dp[p][j-1];
(以i位置為結尾的長度為j的數量)
而這樣的數值可以通過樹狀數組查詢做差即可得到。
至此,這道題主體思想已經有了。
再注意下區間的閉合問題即可,詳見代碼。
*/

ll dp[maxn][15],tree[maxn][15];
int x;

int lowbit(int x)
{
    return x&(-x);
}

void add(int x,int y,ll v)///在指定位置上加數
{
    int tp=x;
    while(y<15)
    {
        for(x=tp;x<maxn;tree[x][y]+=v,x+=lowbit(x));
        y+=lowbit(y);
    }
}

ll  sum(int x,int y)///在指定位置上加數
{
    ll ret=0;
    int tp=x;
    while(y>0)
    {
        for(x=tp;x>0;ret+=tree[x][y],x-=lowbit(x));
        y-=lowbit(y);
    }
    return ret;
}

int n,k;

int main()
{
    scanf("%d%d",&n,&k);k++;

    memset(dp,0,sizeof(dp));
    memset(tree,0,sizeof(tree));

    dp[0][0]=1;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&x);
        if(i==1)
        {
            for(int j=0;j<=k&&j<=i;j++)
            {
                if(j==0) dp[i][j]+=dp[i-1][j];
                else if (j==1)
                {
                    dp[i][j]=1;
                    add(x,j,dp[i][j]);///等于号是要取到的,是以原位操作無偏移
                }
            }
            continue;
        }

        for(int j=0;j<=k&&j<=i;j++)
        {
            if(j==0) dp[i][j]=dp[i-1][j];
            else
            {
                if(j==1) dp[i][j]=1;///怎麼算都是一,因為是計算以目前數字開頭的
                else   dp[i][j]=sum(x-1,j-1)-sum(x-1,j-2);///比x小的dp值的字首統計
                add(x,j,dp[i][j]);
            }
        }
    }
    ll ans=0;
    for(int i=1;i<=n;i++) ans+=dp[i][k];
    printf("%lld\n",ans);
    return 0;
}