Problem F: Best string Orz~
Time Limit: 3 Sec Memory Limit: 64 MBSubmit: 3 Solved: 1
[ Submit][ Status][ Web Board]
Description
If a string S is made up by n1 'O',n2 'r', n3 'z' and n4 '~',(n1>=n2>=n3>=n4),and for all of its prefix substring C,if in C the number of 'O' is larger or equal than the number of 'r',the number of 'r' is larger or equal than the number of 'z' and the number of 'z' is larger or equal than the number of '~',then we call it best string.
Now give you the n1,n2,n3,n4,I wonder how many best strings are there with only n1 'O',n2 'r',n3 'z',n4 '~';
Input
There are more than one input.
Each input is four number n1,n2,n3,n4,end by four zeros,which shouldn't be processed.(0<=n1,n2,n3,n4<10)
Output
For each input,print the number of best string.
Sample Input
1 1 1 1 4 3 2 1 1 2 3 0 0 0 0 0
Sample Output
1 768 0
HINT
Append Code
/****
解题思路:
一看题目发现显然是个动态规划问题;
递推关系:
dp[i][j][k][l]=dp[i-1][j][k][l]+dp[i][j-1][k][l]+dp[i][j][k-1][l]+dp[i][j][k][l-1].
dp[i][j][k][l]指的是:S字符串由i个O,j个r,k个z,l个~组成,这样的S串的个数。
解释:
假设我们已经知道某个S串的dp值,那strlen(s)+1个的S串也就可以推出来,将原来的S串分为四种串,
第一种最后一个是O,第二种最后一个是r,第三种最后一个是z,第四种最后一个是~。
但是,可能其中某些情况不存在,那也没事,那些情况对应的dp值为0.照样可以算。
这道题可以算是动态规划了。
****/
#include <cstdio>
#include <cmath>
#include <cstring>
#include <iostream>
using namespace std;
int n[4]= {0};
long long dp[11][11][11][11]= {0};
long long ans=0;
int read()
{
scanf("%d%d%d%d",&n[1],&n[2],&n[3],&n[4]);
if(n[1]+n[2]+n[3]+n[4]==0)
return 0;
else
return 1;
}
int f(int a,int b,int c,int d)
{
if(!(a>=0&&b>=0&&c>=0&&d>=0))
return 0;
if(a>=b&&b>=c&&c>=d)
return 1;
else
return 0;
}
void DP()
{
int i,j,k,l;
memset(dp,0,sizeof(dp));
dp[0][0][0][0]=1;
for(l=0; l<=n[4]; l++)
for(k=0; k<=n[3]; k++)
for(j=0; j<=n[2]; j++)
for(i=0; i<=n[1]; i++)
{
if(!f(i,j,k,l))
continue;
if(f(i,j,k,l-1))
dp[i][j][k][l]+=dp[i][j][k][l-1];
if(f(i,j,k-1,l))
dp[i][j][k][l]+=dp[i][j][k-1][l];
if(f(i,j-1,k,l))
dp[i][j][k][l]+=dp[i][j-1][k][l];
if(f(i-1,j,k,l))
dp[i][j][k][l]+=dp[i-1][j][k][l];
//printf("%d %d %d %d::%d\n",i,j,k,l,dp[i][j][k][l]);
}
}
void print()
{
ans=dp[n[1]][n[2]][n[3]][n[4]];
printf("%lld\n",ans);
}
int main()
{
n[1]=10;n[2]=10;n[3]=10;n[4]=10;
DP();
while(read())
{
if(!f(n[1],n[2],n[3],n[4]))
ans=0;
print();
}
return 0;
}