HDU - 5542 The Battle of Chibi 離散化+dp+樹狀數組

題目鏈接

題意:給出一個長爲n的序列,求其中長爲m的嚴格單調上升序列的個數。

思路:dp[i][j],表示以i爲結尾長爲j的序列的個數。由於i最大有1e9,所以離散化,這樣i最大就只有1000。

那麼狀態轉移方程爲:

 dp[i][j] = \sum_{k=1}^{i-1}dp[k][j-1]

這樣時間複雜度就有n^{3},對於轉移方程裏的區間求和,可以通過樹狀數組維護(線段樹空間不夠),這樣複雜度就到了n^{2}logn

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<queue>
#include<deque>
using namespace std;
#define ll long long
#define PI acos(-1)
#define INF 0x3f3f3f3f
#define NUM 1005
#define debug true
#define lowbit(x) ((-x)&x)
#define ffor(i,d,u) for(int i=(d);i<=(u);++i)
#define _ffor(i,u,d) for(int i=(u);i>=(d);--i)
#define mst(array,Num,Kind,Count) memset(array,Num,sizeof(Kind)*(Count))
const int P = 1e9+7;
int T;
int n,m;
int a[NUM],b[NUM];
map < int , int > ma;
int dp[NUM][NUM],tree[NUM][NUM];
template <typename T>
void read(T& x)
{
    x=0;
    char c;T t=1;
    while(((c=getchar())<'0'||c>'9')&&c!='-');
    if(c=='-'){t=-1;c=getchar();}
    do(x*=10)+=(c-'0');while((c=getchar())>='0'&&c<='9');
    x*=t;
}
template <typename T>
void write(T x)
{
    int len=0;char c[21];
    if(x<0)putchar('-'),x*=(-1);
    do{++len;c[len]=(x%10)+'0';}while(x/=10);
    _ffor(i,len,1)putchar(c[i]);
}
void AC()
{
    read(T);
    int t = 0,x,y,sum,len;
    while(T--)
    {
        ++t;
        ma.clear();
        ffor(i,1,n)ffor(j,1,m)dp[i][j] = tree[i][j] = 0;
        read(n),read(m);
        ffor(i,1,n)read(a[i]),b[i] = a[i];
        sort(b+1,b+1+n);
        len = 0;
        ffor(i,1,n)if(ma[b[i]] == 0)ma[b[i]] = ++len;
        ffor(i,1,n)
        {
            x = ma[a[i]];
            (++dp[x][1]) %= P;
            y = x;
            while(y <= n)
            {
                (++tree[y][1]) %= P;
                y += lowbit(y);
            }
            ffor(j,2,min(x,m))
            {
                sum = 0;
                y = x-1;
                while(y)
                {
                    (sum += tree[y][j-1]) %= P;
                    y -= lowbit(y);
                }
                (dp[x][j] += sum) %= P;
                y = x;
                while(y <= n)
                {
                    (tree[y][j] += sum) %= P;
                    y += lowbit(y);
                }
            }
        }
        sum = 0;
        ffor(i,m,len)(sum += dp[i][m]) %= P;
        printf("Case #%d: %d\n",t,sum);
    }
}
int main()
{
    AC();
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章