【DP】 HDOJ 4991 Ordered Subsequence

先推出一个复杂度为n^2*m的DP公式,然后用树状数组优化一下就行了。。。

#include <iostream>  
#include <queue>  
#include <stack>  
#include <map>  
#include <set>  
#include <bitset>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <climits>  
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 10015
#define maxm 40005
#define eps 1e-10
#define mod 123456789
#define INF 999999999
#define lowbit(x) (x&(-x))
#define mp mark_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid  
#define rson o<<1 | 1, mid+1, R  
//typedef vector<int>::iterator IT;
typedef long long LL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
void scanf(int &__x){__x=0;char __ch=getchar();while(__ch==' '||__ch=='\n')__ch=getchar();while(__ch>='0'&&__ch<='9')__x=__x*10+__ch-'0',__ch = getchar();}
LL gcd(LL _a, LL _b){if(!_b) return _a;else return gcd(_b, _a%_b);}
// head
//POJ 1330

int dp[maxn][105], num[maxn];
int tree[105][maxn];
int n, m, mx;
struct node
{
	int id, v;
}po[maxn];
int cmp(node a, node b)
{
	return a.v < b.v;
}
void read(void)
{
	for(int i = 1; i <= n; i++) scanf("%d", &po[i].v), po[i].id = i;
	sort(po+1, po+1+n, cmp);
	po[0].v = -INF;
	int cnt = 2;
	for(int i = 1; i <= n; i++) 
		if(po[i].v != po[i-1].v) num[po[i].id] = ++cnt;
		else num[po[i].id] = cnt;
	mx = cnt;
}
void add(int tm, int x, int v)
{
	for(int i = x; i <= mx; i += lowbit(i)) {
		tree[tm][i] = tree[tm][i] + v;
		if(tree[tm][i] > mod) tree[tm][i] -= mod;
	}
}
int sum(int tm, int x)
{
	int ans = 0;
	for(int i = x; i > 0; i -= lowbit(i)) {
		ans = ans + tree[tm][i];
		if(ans > mod) ans -= mod;
	}
	return ans;
}
void debug(void)
{
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= m; j++)
            printf("%d ", dp[i][j]);
        printf("\n");
    }
}
void work(void)
{
	memset(tree, 0, sizeof tree);
	for(int i = 0; i <= n; i++)
		for(int j = 0; j <= m; j++)
			dp[i][j] = 0;
	for(int i = 1; i <= n; i++) {
		for(int j = 1; j <= m; j++) {
			dp[i][j] = sum(j-1, num[i] - 1);
			add(j, num[i], dp[i][j]);
		}
		dp[i][1] = 1;
		add(1, num[i], dp[i][1]);
	}
	int ans = 0;
    for(int i = 1; i <= n; i++) {
        ans += dp[i][m];
        if(ans > mod) ans -= mod;
    }
	printf("%d\n", ans);
}
int main(void)
{
	while(scanf("%d%d", &n, &m)!=EOF) {
		read();
		work();
	}
	return 0;
}


你可能感兴趣的:(HDU)