现在的位置: 首页 > 综合 > 正文

ural 1523 K-inversions(dp+树状数组)

2014年09月29日 ⁄ 综合 ⁄ 共 1399字 ⁄ 字号 评论关闭

1523. K-inversions

Time limit: 1.0 second
Memory limit: 64 MB
Consider a permutation a1a2,
…, an (all ai are different integers in range from 1 to n). Let us call k-inversion a
sequence of numbers i1i2, …, ik such
that 1 ≤ i1 < i2 < … < ik ≤ n andai1 > ai2 > … > aik.
Your task is to evaluate the number of different k-inversions in a given permutation.

Input

The first line of the input contains two integers n and k (1 ≤ n ≤ 20000, 2 ≤ k ≤ 10). The second line is filled with n numbers ai.

Output

Output a single number — the number of k-inversions in a given permutation. The number must be taken modulo 109.

Samples

input output
3 2
3 1 2
2
5 3
5 4 3 2 1
10

题意:求长度为k的不连续的严格递减子序列的总个数

题解:可以设dp【i】【j】表示以i结尾长度为j的子序列的个数,那么更新就是dp【i】【j】=∑dp【k】【j-1】,其中k<i,而且a【k】>a【i】。而要更新dp值,可以用树状数组维护,按顺序插入序列值,那么树状数组的值就可以表示比它小的长度为j-1的所有子序列的和,这样就可以在logn的时间更新dp值了,所以总复杂度是O(n*k*logn)

#include<stdio.h>
#include<string.h>
#define MAXN 20008
#define mod 1000000000
int a[MAXN],tree[MAXN],dp[MAXN][13];
int low_bit(int x){ return x&(-x); }
void add(int x,int y,int n)
{
    while(x<=n)
    {
        tree[x]=(tree[x]+y)%mod;
        x+=low_bit(x);
    }
}
int query(int x)
{
    int res=0;
    while(x)
    {
        res=(res+tree[x])%mod;
        x-=low_bit(x);
    }
    return res;
}
int main()
{
    int i,j,n,k,res;

    while(scanf("%d%d",&n,&k)>0)
    {
        for(i=1;i<=n;i++)
        {
            scanf("%d",a+i);
            dp[i][1]=1;
        }
        for(i=1,j=n;i<j;i++,j--) res=a[i],a[i]=a[j],a[j]=res;
        for(i=2;i<=k;i++)
        {
            memset(tree,0,sizeof(tree));
            for(j=1;j<=n;j++)
            {
                dp[j][i]=query(a[j]);
                add(a[j],dp[j][i-1],n);
            }
        }
        for(res=0,i=1;i<=n;i++) res=(res+dp[i][k])%mod;
        printf("%d\n",res);
    }

    return 0;
}

抱歉!评论已关闭.