Description
In the New Year2014, Xiao Ming is thinking about the question: give two integers N
and K, Calculate thenumber of the numbers of satisfy the following conditions:
1. It is a positiveinteger and is not greater than N.
2. Xor value of itsall digital is K.
For example N = 12,K = 3, the number of satisfy condition is 3 and 12
(3 = 3, 1 ^ 2 = 3).
In order to let XiaoMing happy in the New Year 2014, can you help him?
Input
There are multipletest cases, each test sample contains two positive integers N and
K (0 <= N, K< 10 ^ 18), End to file.
Output
For each case,output the number of the numbers of satisfy condition in one line.
Sample Input
12 3
999 5
12354 8
Sample Output
2
76
662
题目大意:给定一个N和一个K。求出1到N的所有数中,每位进行按位异或后得到K的数的个数。
当时比赛的时候,看着题就发现党K大于15的时候答案为0.因为每一位进行按位异或运算始终是0到9的数字在进行,最大能得到15.但是,后面就傻逼了。因为之前写一个数位DP超时了,想了想就没写。。。。。。真是可惜。
dp[i][j][0/1]表示的是长度为i,当前异或值是j,0表示到上界,1表示不到上界。
#include<cstdio>
#include<cstring>
int k;
char n[20];
__int64 dp[20][20][2] ,ans;
int main()
{
while(~scanf("%s%d",&n,&k))
{
memset(dp,0,sizeof(dp));
if(n[0]=='0')
{
printf("0\n");
}
else if(k > 15)
{
printf("0\n");
}
else
{
int len = strlen(n);
int re;
for(int i = 0;i < n[0] - '0';i++)
{
dp[1][i][0] = 1;
}
dp[1][n[0]-'0'][1] = 1;
for(int i = 2;i <= len;i++)
{
re = n[i - 1] - '0';
for(int r = 15;r>=0;r--)
{
for(int j = 0;j < re;j++)
{
dp[i][r][0] += dp[i-1][r^j][0];
dp[i][r][0] += dp[i-1][r^j][1];
}
dp[i][r][0] += dp[i-1][r^re][0];
dp[i][r][1] += dp[i-1][r^re][1];
for(int j = re + 1;j < 10;j++)
{
dp[i][r][0] += dp[i-1][r^j][0];
}
}
}
ans = dp[len][k][0] + dp[len][k][1];
if(!k)
{
ans--;
}
printf("%I64d\n",ans);
}
}
return 0;
}