SPOJ 10606 Balanced Numbers - 数位dp
题目大意:
一个数被称为是平衡的数当且仅当对于所有出现过的数位, 偶数出现奇数次,奇数出现偶数次。 给定 A,B,请统计出 [A,B] 内所有平衡的数的个数。
1 ≤A≤B≤
分析:
- 是个数位dp。
- (n)为[1,n]中所有平衡的数的个数,则原问题<=>求p(B)-p(A-1)。
- 注意到要填的数字只有0~9(注意不能有前导0,程序中要特判),
用0表示这个数字没有出现过,1表示这个数字出现奇数次,2表示这个数字出现偶数次,用一个10位的3进制数就可以表示出状态,记为S。由于个人觉得3进制不好直接取位,用的4进制表示,但是4进制的状态数410 太大了,就只好使用了hash,建立hash表来做。 - 设dp[i][S][0/1]:
S是当前的状态,
0表示所有状态代表的数的前i位严格小于n的前i位的方案数;1表示所有状态代表的数的前i位等于n的前i位的方案数
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define MAXBIT 19
#define MAXST 59049 //3^10
typedef long long LL;
struct HashMap{
int cnth[2],st[MAXST+10][2],id[MAXST+10][2];
LL dp[MAXST+10][2];
void Clear(){
memset(id,-1,sizeof id);
memset(st,0,sizeof st);
memset(dp,0,sizeof dp);
cnth[0]=cnth[1]=0;
}
void Insert(LL S,LL dpval,int d){
if(id[S][d]==-1){
id[S][d]=++cnth[d];
st[cnth[d]][d]=S;
}
dp[id[S][d]][d]+=dpval;
}
}var[2],*last=&var[0],*cur=&var[1];
LL a,b,pw[MAXBIT+10];
int col[MAXBIT+10],lmt[MAXBIT+10];
int Getorg(LL x){
int ret=0,k=0;
LL y=x;
memset(lmt,0,sizeof lmt);
while(x){
k++;
x/=10;
}
while(y){
lmt[k-ret]=y%10;
y/=10;
ret++;
}
return ret;
}
inline void Getbit(LL s){
memset(col,0,sizeof col);
for(int i=0;i<=9;i++){
col[i]=s%3;
s/=3;
}
}
LL DP(LL R)
{
int n=Getorg(R);
if(!n) return 1;
last->Clear();
for(int k=1;k<lmt[1];k++)
last->Insert(pw[k],1,0);
last->Insert(pw[lmt[1]],1,1);
last->Insert(0,1,0);
for(int i=2;i<=n;i++){
cur->Clear();
for(int j=1;j<=last->cnth[0];j++){
Getbit(last->st[j][0]);
for(int k=0;k<=9;k++){
if(last->st[j][0]==0&&k==0)
continue;
if(col[k]!=2)
cur->Insert(last->st[j][0]+pw[k],last->dp[j][0],0);
else
cur->Insert(last->st[j][0]-pw[k],last->dp[j][0],0);
}
}
for(int j=1;j<=last->cnth[1];j++){
Getbit(last->st[j][1]);
for(int k=0;k<lmt[i];k++){
if(last->st[j][1]==0&&k==0)
continue;
if(col[k]!=2)
cur->Insert(last->st[j][1]+pw[k],last->dp[j][1],0);
else
cur->Insert(last->st[j][1]-pw[k],last->dp[j][1],0);
}
if(lmt[i]==0&&last->st[j][1]==0)
continue;
if(col[lmt[i]]!=2)
cur->Insert(last->st[j][1]+pw[lmt[i]],last->dp[j][1],1);
else
cur->Insert(last->st[j][1]-pw[lmt[i]],last->dp[j][1],1);
}
cur->Insert(0,1,0);
swap(cur,last);
}
LL ret=0;
for(int d=0;d<2;d++){
for(int i=1;i<=last->cnth[d];i++){
Getbit(last->st[i][d]);
bool flag=true;
for(int j=0;j<=9;j++){
if(j&1){
if(col[j]&&col[j]&1){
flag=false;
break;
}
}
else{
if(col[j]&&(!(col[j]&1))){
flag=false;
break;
}
}
}
if(flag)
ret+=last->dp[i][d];
}
}
return ret;
}
void prepare()
{
pw[0]=1;
for(int i=1;i<=9;i++)
pw[i]=pw[i-1]*3;
}
int main()
{
int T;
scanf("%d",&T);
prepare();
while(T--){
scanf("%lld%lld",&a,&b);
printf("%lld\n",DP(b)-DP(a-1));
}
}