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.
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.
Print one integer — the answer to the problem.
5 2 1 2 3 5 4
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]);
}
}