SPOJ10606 BALNUM

来源:互联网 发布:看板设计软件 编辑:程序博客网 时间:2024/06/05 08:33

题意:求出现的数字,所有偶数出现奇数次,所有奇数出现偶数次。比如211是对的,因为1是奇数出现了两次,2是偶数出现了奇数次。


思路:数位dp枚举到个位,所形成的数对其进行判断,有三种情况(利用三进制)0表示这个数还没出现,1表示出现为偶数,2表示出现为奇数。


代码:

#include <string.h>#include <stdio.h>#include <iostream>#include <algorithm>using namespace std;typedef long long LL;LL dp[20][60000];int bit[20];bool check(int s){    int num[10];    for(int i=0;i<10;i++)    {        num[i]=s%3;        s/=3;    }    for(int i=0;i<10;i++)    {        if(num[i]!=0)        {            if(i%2==0&&num[i]==2)return false;//偶数数字出现了奇数次,舍去            if(i%2==1&&num[i]==1)return false;//奇数数字出现了偶数次,舍去        }    }    return true;}int getnews(int x,int s){    int num[10];    for(int i=0;i<10;i++)    {        num[i]=s%3;        s/=3;    }    if(num[x]==0)        num[x]=1;    else        num[x]=3-num[x];    int news=0;    for(int i=9;i>=0;i--)    {        news*=3;        news+=num[i];    }    return news;}LL dfs(int pos,int s,int flag,int z){    if(pos==-1)    {//        if(check(s))//            cout<<s<<endl;        return check(s);    }    if(!flag&&dp[pos][s]!=-1)        return dp[pos][s];    LL ans=0;    int end=flag?bit[pos]:9;    for(int i=0;i<=end;i++)    {        ans+=dfs(pos-1,(z&&i==0)?0:getnews(i,s),flag&&i==end,z&&i==0);    }    if(!flag)dp[pos][s]=ans;    return ans;}LL solve(LL n){    int len=0;    while(n)    {        bit[len++]=n%10;        n/=10;    }    return dfs(len-1,0,1,1);}int main(){    int T;    memset(dp,-1,sizeof(dp));    LL a,b;    scanf("%d",&T);    while(T--)    {        scanf("%lld%lld",&a,&b);        printf("%lld\n",solve(b)-solve(a-1));    }    return 0;}


原创粉丝点击