Codeforces 597C Subsequences【Dp+二维树状数组】

C. Subsequences
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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

题目大意:


一共有N个数,让你找一个长度为K+1的严格递增子序列(没必要连续),问一共有多少个子序列满足条件。


思路:


很老套路的题了。

我们需要维护k+1棵树状数组,用来求一个前缀和。


设定Dp【i】【j】表示到位子i,以a【i】结尾的序列,已经找到了严格递增的j个数的满足条件的个数。


那么有:

dp【i】【j】+=dp【k】【j-1】(k<i&&a[k]<a[i]);


直接暴力转移肯定要超时,所以维护K+1个树状数组求一个Dp前缀和即可。


Ac代码:


#include<stdio.h>
#include<string.h>
using namespace std;
#define ll __int64
ll tree[15][150000];
ll dp[150000][15];
ll a[150000];
ll lowbit(ll x)
{
    return x&(-x);
}
void update(ll x,ll y,ll d)
{
    ll temp=y;
    while(x<=11)
    {
        y=temp;
        while(y<=100000)
        {
            tree[x][y]+=d;
            y=y+lowbit(y);
        }
        x=x+lowbit(x);

    }

}
ll getsum(ll x,ll y)
{
    ll sum=0;
    ll temp=y;
    while(x>0)
    {
        y=temp;
        while(y>0)
        {
            sum=sum+tree[x][y];
            y=y-lowbit(y);
        }
        x=x-lowbit(x);
    }
    return sum;
}
int main()
{
    ll n,k;
    while(~scanf("%I64d%I64d",&n,&k))
    {
        k++;
        memset(tree,0,sizeof(tree));
        memset(dp,0,sizeof(dp));
        for(ll i=1;i<=n;i++)scanf("%I64d",&a[i]);
        dp[0][0]=1;
        for(ll i=1;i<=n;i++)
        {
            for(ll j=0;j<=k&&j<=i;j++)
            {
                if(i==1)
                {
                    if(j==0)dp[i][j]+=dp[i-1][j];
                    else if(j==1)
                    {
                        dp[i][j]=1;
                        update(j,a[i],1);
                    }
                    continue;
                }
                if(j==0)dp[i][j]+=dp[i-1][j];
                else
                {
                    if(j==1)dp[i][j]+=dp[i-1][j-1];
                    if(j>=2)dp[i][j]+=getsum(j-1,a[i]-1)-getsum(j-2,a[i]-1);
                    update(j,a[i],dp[i][j]);
                }
            }
        }
        ll output=0;
        for(ll i=1;i<=n;i++)output+=dp[i][k];
        printf("%I64d\n",output);
        //prllf("%I64d\n",dp[n][k]);
    }
}







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值