K - Balanced Numbers SPOJ - BALNUM 数位dp+状压

K - Balanced Numbers

  SPOJ - BALNUM 

https://cn.vjudge.net/problem/SPOJ-BALNUM

Balanced numbers have been used by mathematicians for centuries. A positive integer is considered a balanced number if:

1)      Every even digit appears an odd number of times in its decimal representation

2)      Every odd digit appears an even number of times in its decimal representation

For example, 77, 211, 6222 and 112334445555677 are balanced numbers while 351, 21, and 662 are not.

Given an interval [A, B], your task is to find the amount of balanced numbers in [A, B] where both A and B are included.

Input

The first line contains an integer T representing the number of test cases.

A test case consists of two numbers A and B separated by a single space representing the interval. You may assume that 1 <= A <= B <= 1019 

Output

For each test case, you need to write a number in a single line: the amount of balanced numbers in the corresponding interval

Example

Input:
2
1 1000
1 9
Output:
147
4

题意:在下列情况下,正整数被认为是一个平衡数字
1,每个偶数在其十进制表示中出现奇数次

2,每个奇数在其十进制表示中出现偶数次

给定一个区间[A,B],你的任务是在[A,B]中找到包含A和B的平衡数字的数量?

思路:数位dp,共有10个数字,每个数字有三个状态,0.没出现,1出现奇数次,2.出现偶数次。所以总共的状态有3^10=59000+,

int dp[21][60000];    

#include <iostream>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <queue>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
typedef long long LL;
const LL mod=1e9+7;
const int M=13;
using namespace std;
const int N =1e5+100;
LL dp[21][60000];//dp[pos][sta]
int v[20],a[21];//v[i]表示3^i
LL K(int x)//判断状态是否满足题意
{
    for(int i=0;x&&i<=9;i++,x/=3)
    {
        if(x%3==0) continue;
        else if(x%3==1) {if(i&1) return 0;}
        else {if(i%2==0) return 0;}
    }
    return 1;
}
int getsta(int sta,int i)
{
    if(i==0&&sta==0) return 0;//排除前导0的影响
    int x=(sta%(v[i]*3))/v[i];//x为数字i出现的状态
    if(x<=1) return sta+v[i];
    return sta-v[i];
}
LL dfs(int pos,int sta,int limit)//数位dp板子
{
    if(pos==-1) return K(sta);
    if(!limit&&~dp[pos][sta]) return dp[pos][sta];
    int up=limit?a[pos]:9;
    LL ans=0;
    for(int i=0;i<=up;i++)
        ans+=dfs(pos-1,getsta(sta,i),limit&&i==up);
    return limit?ans:dp[pos][sta]=ans;
}
LL slove(LL x)
{
    int pos=0;
    for(;x;x/=10)
        a[pos++]=x%10;
    return dfs(pos-1,0,1);
}
int main()
{
    mem(dp,-1);
    v[0]=1;
    for(int i=1;i<=10;i++)
        v[i]=v[i-1]*3;
    int t;
    scanf("%d",&t);
    while(t--)
    {
        LL l,r;
        scanf("%lld%lld",&l,&r);
        printf("%lld\n",slove(r)-slove(l-1));
    }
}





猜你喜欢

转载自blog.csdn.net/xiangaccepted/article/details/80515465
今日推荐