Two Arrays
Problem Description
You are given two integers n and m. Calculate the number of pairs of arrays (a,b) such that:
- the length of both arrays is equal to m;
- each element of each array is an integer between 1 and n (inclusive);
- ai ≤ bi for any index i from 1 to m;
- array a is sorted in non-descending order;
- array b is sorted in non-ascending order.
As the result can be very large, you should print it modulo 109+7.
Input
The only line contains two integers n and m (1 ≤ n ≤ 1000, 1 ≤ m ≤ 10).
Output
Print one integer – the number of arrays a and b satisfying the conditions described above modulo 109+7.
Sample Input
2 2
Sample Output
5
题意
有两个数组 a 和 b,每个数组都有 m 个元素,每个元素的值都要是1~n的整数,a序列非递减,b序列非递增,要求 a i ≤ b i a_i \le b_i ai≤bi,求共有多少种满足要求的方案。
题解:
设数组dp,
d
p
[
i
]
[
j
]
[
k
]
dp[i][j][k]
dp[i][j][k]代表a的第 k 位为 i ,b的第k位为 j时有多少种方案。因为a数组非递减,b数组非递增,当前状态可以是第k-1位,所有1<=ak-1<=i且j<=bk-1<=n的和。 所以递推式为:
d
p
[
i
]
[
j
]
[
k
]
=
∑
a
=
1
i
∑
b
=
j
n
d
p
[
a
]
[
b
]
[
k
−
1
]
dp[i][j][k] = \sum\limits_{a=1}^i\sum\limits_{b=j}^ndp[a][b][k-1]
dp[i][j][k]=a=1∑ib=j∑ndp[a][b][k−1]
如果暴力求和的话复杂是O(n4m)。式子右边的部分,可以通过前缀和来维护,那样就能在 O(1) 的时间内得到式子右边的结果,所以在第 k 位计算完成后,可以维护当前层的前缀和,以便后面的状态转移。这样就能在 O(n2m) 完成状态转移。
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<ctype.h>
#include<cstring>
#include<vector>
#include<deque>
#include<map>
#include<iostream>
#include<iterator>
#define dbg(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
#define eps 1e-8
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 1020;
const int mod = 1000000007;
LL dp[maxn][maxn][12], sum[maxn][maxn];
void getsum(int n, int k);
int main()
{
int n, m, i, j, k;
scanf("%d %d", &n, &m);
for(i=1;i<=n;i++)
for(j=i;j<=n;j++)
dp[i][j][1] = 1;
getsum(n, 1);
for(k=2;k<=m;k++)
{
for(i=1;i<=n;i++)
for(j=i;j<=n;j++)
dp[i][j][k] = sum[i][j];
getsum(n, k);
}
printf("%I64d\n", sum[n][1]);
return 0;
}
//求当前层前缀和
void getsum(int n, int k)
{
int i, j;
for(i=1;i<=n;i++)
{
sum[i][n+1] = 0;
for(j=n;j>=1;j--)
sum[i][j] = (sum[i][j+1]+dp[i][j][k])%mod;
}
for(i=2;i<=n;i++)
for(j=n;j>=1;j--)
sum[i][j] = (sum[i][j]+sum[i-1][j])%mod;
}