hdu5456 Matches Puzzle Game

题意:给出n个火柴棒,问能摆成多少个a-b=c的等式,其中,a,b,c均为正整数。

做法:dp[i][j][cr][b][c],当前用了i个火柴棒,从低位到高位,已经考虑到了第j位,cr代表j-1位是否给j位贡献了一个1,b代表数字b是否已经到了最高位,c代表数字c是否已经到了最高位。有多少种方法到达目标状态。不断枚举在j位的数字进行数位dp即可。由于j肯定是不断在增大的,所以写的时候可以直接舍去这维。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
int n;
int a[10]={6,2,5,5,4,5,6,3,7,6};
ll m;
ll dp[510][2][2][2];
ll dfs(int num,int cr,int b,int c)
{
	if(num>n)
		return 0;
	if(num+a[1]==n&&cr==1&&b==1&&c==1)
		return 1;
	if(num==n)
	{
		if(cr==0&&b==1&&c==1)
			return 1;
		return 0;
	}
	if(dp[num][cr][b][c]!=-1)
		return dp[num][cr][b][c];
	dp[num][cr][b][c]=0;
	if(b==0)
	{
		if(c==0)
		{
			for(int i=0;i<10;i++)
				for(int j=0;j<10;j++)
				{
					int t=a[i]+a[j]+a[(i+j+cr)%10];
					dp[num][cr][b][c]+=dfs(num+t,(i+j+cr)/10,0,0);
					if(i!=0)
						dp[num][cr][b][c]+=dfs(num+t,(i+j+cr)/10,1,0);
					if(j!=0)
						dp[num][cr][b][c]+=dfs(num+t,(i+j+cr)/10,0,1);
					if(i!=0&&j!=0)
						dp[num][cr][b][c]+=dfs(num+t,(i+j+cr)/10,1,1);
					dp[num][cr][b][c]%=m;
				}
		}
		else
		{
			for(int i=0;i<10;i++)
			{
				int t=a[i]+a[(i+cr)%10];
				dp[num][cr][b][c]+=dfs(num+t,(i+cr)/10,0,1);
				if(i!=0)
					dp[num][cr][b][c]+=dfs(num+t,(i+cr)/10,1,1);
			}
		}
	}
	else
	{
		if(c==0)
		{
			for(int i=0;i<10;i++)
			{
				int t=a[i]+a[(i+cr)%10];
				dp[num][cr][b][c]+=dfs(num+t,(i+cr)/10,1,0);
				if(i!=0)
					dp[num][cr][b][c]+=dfs(num+t,(i+cr)/10,1,1);
			}
		}
	}
	return dp[num][cr][b][c]%=m;
}
int main()
{
	int T;
	scanf("%d",&T);
	for(int cs=1;cs<=T;cs++)
	{
		cin>>n>>m;
		n-=3;
		memset(dp,-1,sizeof(dp));
		printf("Case #%d: %d\n",cs,int(dfs(0,0,0,0)));
	}
}


Time Limit: 3000/2000 MS (Java/Others)    Memory Limit: 65535/102400 K (Java/Others)
Total Submission(s): 107    Accepted Submission(s): 70


Problem Description
As an exciting puzzle game for kids and girlfriends, the Matches Puzzle Game asks the player to find the number of possible equations  AB=C with exactly  n (5n500) matches (or sticks).

In these equations,  A,B and  C are positive integers. The equality sign needs two matches and the sign of subtraction needs just one. Leading zeros are not allowed.

Please answer the number, modulo a given integer  m (3m2×109).
 

Input
The input contains several test cases. The first line of the input is a single integer  t which is the number of test cases. Then  t (1t30) test cases follow.

Each test case contains one line with two integers  n (5n500) and  m (3m2×109).
 

Output
For each test case, you should output the answer modulo  m.
 

Sample Input

4 12 1000000007 17 1000000007 20 1000000007 147 1000000007
 

Sample Output

Case #1: 1 Case #2: 5 Case #3: 38 Case #4: 815630825
 

Source
2015 ACM/ICPC Asia Regional Shenyang Online

你可能感兴趣的:(数位Dp)