您的位置:首页 > 其它

hdu 4991(树状数组优化dp)

2016-06-19 21:09 267 查看

Ordered Subsequence

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

[align=left]Problem Description[/align]
A numeric sequence of ai is ordered if a1<a2<……<aN. Let the subsequence of the given numeric sequence (a1, a2,……, aN) be any sequence (ai1, ai2,……,
aiK), where 1<=i1<i2 <……<iK<=N. For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, eg. (1, 7), (3, 4, 8) and many others.

Your program, when given the numeric sequence, must find the number of its ordered subsequence with exact m numbers.
 

[align=left]Input[/align]
Multi test cases. Each case contain two lines. The first line contains two integers n and m, n is the length of the sequence and m represent the size of the subsequence you need to find. The second line contains the elements of sequence
- n integers in the range from 0 to 987654321 each.

Process to the end of file.
[Technical Specification]

1<=n<=10000

1<=m<=100
 

[align=left]Output[/align]
For each case, output answer % 123456789.
 

[align=left]Sample Input[/align]

3 2
1 1 2
7 3
1 7 3 5 9 4 8

 

[align=left]Sample Output[/align]

2
12

 
解题思路:这道题和hdu 5542完全一样,长度为m的递增子序列的个数,树状数组+dp。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<set>
#include<map>
using namespace std;

const int maxn = 10005;
const int mod = 123456789;
int n,m;
int tree[105][maxn],a[maxn];
set<int> Set;
map<int,int> Map;

int lowbit(int x)
{
return x & -x;
}

void update(int i,int x,int c)
{
while(x <= n)
{
tree[i][x] = (tree[i][x] + c) % mod;
x += lowbit(x);
}
}

int getsum(int i,int x)
{
int sum = 0;
while(x > 0)
{
sum = (sum + tree[i][x]) % mod;
x -= lowbit(x);
}
return sum;
}

int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
Map.clear();
Set.clear();
memset(tree,0,sizeof(tree));
for(int i = 1; i <= n; i++)
{
scanf("%d",&a[i]);
Set.insert(a[i]);
}
int cnt = 0;
for(set<int>::iterator it = Set.begin(); it != Set.end(); it++)
Map[*it] = ++cnt;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
{
int tmp = 0;
if(j == 1) tmp = 1;
else tmp = (tmp + getsum(j-1,Map[a[i]]-1)) % mod;
update(j,Map[a[i]],tmp);
}
printf("%d\n",getsum(m,cnt));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dp