HDU 3652 B-number (数位DP)

B-number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4413    Accepted Submission(s): 2540

Problem Description
A wqb-number, or B-number for short, is a non-negative integer whose decimal form contains the sub- string "13" and can be divided by 13. For example, 130 and 2613 are wqb-numbers, but 143 and 2639 are not. Your task is to calculate how many wqb-numbers from 1 to n for a given integer n.

Input
Process till EOF. In each line, there is one positive integer n(1 <= n <= 1000000000).

Output
Print each answer in a single line.
Sample Input
 
   
13 100 200 1000
Sample Output
 
   
1 1 2 2
Author
wqb0039
Source
2010 Asia Regional Chengdu Site —— Online Contest
Recommend
lcy   |   We have carefully selected several similar problems for you:  3651 3655 3654 3653 3659 

题意:求小于n是13的倍数且含有'13'的数的个数。

题解: 数位DP。详细思路参考:初探数位DP

#include
#include 
#include 
#include 
using namespace std;

int dp[11][3][13],bit[12];
//计算 mod 13 余数为 0 的数位DP 
//dp[i][j][k] : i 表示位数 ,j 表示 是否存在1,3的 3 种情况, k表示 余数 
void init()
{
	int i,j,k;
	bit[1]=1;
	for(i=2;i<11;i++)
	{
		bit[i]=bit[i-1]*10; //m[i]=m[i-1]*10%13; 
	}
	dp[0][0][0]=1;
	for(i=1;i<=11;i++) //位数 
	{
		for(j=0;j<=12;j++) 
		{
			for(k=0;k<10;k++)  
			{
				dp[i][0][(j+k*bit[i])%13]+=dp[i-1][0][j];
				dp[i][2][(j+k*bit[i])%13]+=dp[i-1][2][j];
			}
			dp[i][0][(j+bit[i])%13]-=dp[i-1][1][j];
			dp[i][1][(j+bit[i]*3)%13]+=dp[i-1][0][j];
			dp[i][2][(j+bit[i])%13]+=dp[i-1][1][j];
		}
	}
}

int solve(int n)
{
	int digit[15],i,j,ans=0,cnt=0,flag=0,mod=0;
	
	while(n) //计算各位上的数据 
	{
		digit[++cnt]=n%10;
		n/=10;
	}
	
	digit[cnt+1]=0;//让最高前位置0 ,这一步非常重要,
	for(i=cnt;i>=1;mod=(mod+digit[i]*bit[i])%13,--i)
	{
		for(j=0;j1) //(x+m[i]+mod)%13=0,求x%13
		{
			ans+=dp[i-1][1][(13-(mod+bit[i])%13)%13];
			if(digit[i+1] == 1 && digit[i]>3)
			{
				ans+=dp[i][1][(13-mod)%13];
			}
		}
		if(digit[i] == 3 && digit[i+1] == 1)
		{
			flag=1;
		}
	}
	return ans;
}

int main()
{
	int n;
	init();
	while(~scanf("%d",&n))
	{
		printf("%d\n",solve(n+1)); //0到 n 
	}
	return 0;
}


你可能感兴趣的:(HDUOJ,ACM_数位DP)