首页 > 代码库 > hdu 4991(dp+树状数组)
hdu 4991(dp+树状数组)
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=4991
Ordered Subsequence
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 221 Accepted Submission(s): 112
Problem Description
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.
Your program, when given the numeric sequence, must find the number of its ordered subsequence with exact m numbers.
Input
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
Process to the end of file.
[Technical Specification]
1<=n<=10000
1<=m<=100
Output
For each case, output answer % 123456789.
Sample Input
3 2 1 1 2 7 3 1 7 3 5 9 4 8
Sample Output
2 12
思路: dp[i][j]表示一第i个数结尾,长度为j的序列的个数;
那么状态转移方程式:dp[i][j]=sum(dp[k][j-1]);(k<i&&a[i]>a[k])
如果直接遍历,那么时间复杂度至少是O(n*n),超时,所以考虑用树状数组维护一段区间的和;
#include <iostream> #include <stdio.h> #include <string> #include <string.h> #include <cstdio> #include <cmath> #include <algorithm> typedef long long ll; const int mod=123456789; using namespace std; ll a[10100],b[10100],c[10100],dp[10100][110]; int n,m; int lowbit(int t) { return t&(-t); } void modify(int t,ll d) { while(t<=n) { c[t]+=d; t+=lowbit(t); } } ll getsum(int t) { ll ans=0; while(t>0) { ans=(ans+c[t])%mod; t-=lowbit(t); } return ans; } int main() { while(scanf("%d%d",&n,&m)!=EOF) { for(int i=1;i<=n;i++) { scanf("%I64d",&a[i]); b[i]=a[i]; } sort(b+1,b+1+n); memset(dp,0,sizeof(dp)); for(int i=1;i<=n;i++)dp[i][1]=1; for(int j=2;j<=m;j++) { memset(c,0,sizeof(c)); for(int i=1;i<=n;i++) { int indx=lower_bound(b+1,b+1+n,a[i])-b; dp[i][j]=getsum(indx-1); modify(indx,dp[i][j-1]); } } ll cnt=0; for(int i=1;i<=n;i++) { cnt=(cnt+dp[i][m])%mod; } printf("%I64d\n",cnt%mod); } return 0; }
hdu 4991(dp+树状数组)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。