Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had n1 footmen and n2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that k1 footmen standing successively one after another, or there are strictly more than k2 horsemen standing successively one after another. Find the number of beautiful arrangements of the soldiers.
Note that all n1 + n2 warriors should be present at each arrangement. All footmen are considered indistinguishable among themselves. Similarly, all horsemen are considered indistinguishable among themselves.
The only line contains four space-separated integers n1, n2, k1, k2 (1 ≤ n1, n2 ≤ 100, 1 ≤ k1, k2 ≤ 10) which represent how many footmen and horsemen there are and the largest acceptable number of footmen and horsemen standing in succession, correspondingly.
Print the number of beautiful arrangements of the army modulo 100000000 (108). That is, print the number of such ways to line up the soldiers, that no more than k1 footmen stand successively, and no more than k2 horsemen stand successively.
2 1 1 10
1
2 3 1 2
5
2 4 1 1
0
Let's mark a footman as 1, and a horseman as 2.
In the first sample the only beautiful line-up is: 121
In the second sample 5 beautiful line-ups exist: 12122, 12212, 21212, 21221, 22121
n1个1,n2个2,排列;最多只能存在连续k1个1,最多只能存在连续k2个2.
求有几种排列方式
dp[i][j][k],i表示1的数量,j表示2的数量,k表示以1或者2为结尾,这里用1和0表示.
先把他们从1个到k1(k2)个 一个一个加上去排列,知道排列到不符合要求为止.最后以1结尾的用2去排列,
2结尾的用1去排列,把最后的结果(当然是有两种情况的)相加,就是最后的答案.
核心代码:
for(k=1;k<=k1;k++)
dp[i+k][j][1]=(dp[i+k][j][1]+dp[i][j][0])%mod;
for(k=1;k<=k2;k++)
dp[i][j+k][0]=(dp[i][j+k][0]+dp[i][j][1])%mod;
最后是AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#define mod 100000000
using namespace std;
int dp[220][220][3];
int main(){
memset(dp,0,sizeof(dp));
int n1,n2,k1,k2,k;
cin>>n1>>n2>>k1>>k2;
dp[0][0][0]=dp[0][0][1]=1;
for(int i=0;i<=n1;i++){
for(int j=0;j<=n2;j++){
for(k=1;k<=k1;k++)
dp[i+k][j][1]=(dp[i+k][j][1]+dp[i][j][0])%mod;
for(k=1;k<=k2;k++)
dp[i][j+k][0]=(dp[i][j+k][0]+dp[i][j][1])%mod;
}
}
<span style="white-space:pre"> </span>cout<<(dp[n1][n2][0]+dp[n1][n2][1])%mod<<endl;
<span style="white-space:pre"> </span>return 0;
}