题目大意:
Consider a three-parameter recursive function w(a, b, c):
if a <= 0 or b <= 0 or c <= 0, then w(a, b, c) returns:
1
if a > 20 or b > 20 or c > 20, then w(a, b, c) returns:
w(20, 20, 20)
if a < b and b < c, then w(a, b, c) returns:
w(a, b, c-1) + w(a, b-1, c-1) - w(a, b-1, c)
otherwise it returns:
w(a-1, b, c) + w(a-1, b-1, c) + w(a-1, b, c-1) - w(a-1, b-1, c-1)
如果直接用递归函数肯定会tle,到目前为止碰到两种解决方案:
1)先用暴力法列出数值表,找规律,或用数学方法推导,直接找到递推式。
2)在程序开始先算出所有题目要求的数值范围,并保存,在主程序里直接调用就行了。(对于某些递归不适用)。
愚见。。。。。。有时候我自己都表达不清楚,以后发现错误了再修改咯。
这样一来,题目就很简单了。用题目所给的递推式事先算好所有值。
代码如下:
Code
#include<stdio.h>
int a,b,c,m[22][22][22];
void init()
{
for(a=0;a<=20;a++)
for(b=0;b<=20;b++)
for(c=0;c<=20;c++)
m[a][b][c]=1;
for(a=1;a<=20;a++)
for(b=1;b<=20;b++)
for(c=1;c<=20;c++){
if(a < b && b < c)
m[a][b][c]=m[a][b][c-1]+m[a][b-1][c-1]-m[a][b-1][c];
else
m[a][b][c]=m[a-1][b][c]+m[a-1][b-1][c]+m[a-1][b][c-1]-m[a-1][b-1][c-1];
}
}
int main()
{
init();
while(scanf("%d %d %d",&a,&b,&c),a!=-1||b!=-1||c!=-1){
if(a <= 0 || b <= 0 || c <= 0)
printf("w(%d, %d, %d) = %d\n",a,b,c,1);
else if(a > 20 || b > 20 || c > 20)
printf("w(%d, %d, %d) = %d\n",a,b,c,m[20][20][20]);
else
printf("w(%d, %d, %d) = %d\n",a,b,c,m[a][b][c]);
}
}