Ordered Subsequence
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 464 Accepted Submission(s): 216
Problem Description
A numeric sequence of a
i is ordered if a
1<a
2<……<a
N. Let the subsequence of the given numeric sequence (a
1, a
2,……, a
N) be any sequence (a
i1, a
i2,……, a
iK), where 1<=i
1<i
2 <……<i
K<=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
思路:用LIS显然是不行的,dp[i][j]表示序列长度为i,到第j个数的上升序列个数,那么朴素算法需要O(n²*m),肯定不行。
所以我们利用树状数组来优化它即可。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 10050
#define mod 123456789
int c[105][N],a[N],b[N];
int n,m,cnt;
int lowbit(int x)
{
return x&-x;
}
void add(int x,int v,int num)
{
for(int i=x;i<=cnt;i+=lowbit(i))
c[num][i]=(c[num][i]+v)%mod;
}
int sum(int x,int num)
{
int ans=0;
for(int i=x;i;i-=lowbit(i))
ans=(ans+c[num][i])%mod;
return ans;
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
memset(c,0,sizeof(c));
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
b[i]=a[i];
}
sort(b,b+n);
cnt=unique(b,b+n)-b;
for(int i=0;i<n;i++)
{
int dis=lower_bound(b,b+cnt,a[i])-b+1;
add(dis,1,1);
for(int j=2;j<=m;j++)
{
int num=sum(dis-1,j-1);
add(dis,num,j);
}
}
printf("%d\n",sum(cnt,m));
}
return 0;
}