您的位置:首页 > 其它

SPOJ BALNUM Balanced Numbers

2016-03-18 18:08 459 查看
题目链接:http://www.spoj.com/problems/BALNUM/en/

[b]数位DP专题:/article/8966394.html

[/b]

题意:在一个区间内,找出所有满足条件的数的个数(一个数的所有数位中,偶数数字出现奇数次,奇数数字出现偶数次)。



思路:用三进制的10位数表示当前数位出现的状态,每一位如果是0,表示没有出现过,1表示出现奇数次,2表示出现偶数次。

然后注意一下处理前导零的情况即可(如果当前位枚举的数是0,且前面的状态也是0,也就是前面全选的0)。、

最后处理完所有数位判断一下这个状态是不是满足题意。


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod %100000007

int bit[20];
LL dp[20][60000];
int f[60000][10];
int tree_pow[12];
LL L,R;

bool check(int state)
{
int x = 1; // x=1 表示应该出现偶数次  2 出现奇数次
Rrep(i,9,0)
{
if ( f[state][i]!=0 )
{
if ( f[state][i] + x != 3 ) return false;
}
x = 3 - x;
}
return true;
}

int newstate(int state , int k) //在state的状态基础上再出现一次i
{
if ( f[state][k] == 0 || f[state][k] == 1 ) return state+tree_pow[k]; //0变奇数次,奇数次变偶数次

return state-tree_pow[k];//偶数次变奇数次
}

LL dfs(int pos , int state , bool flag) //处理到第pos位,前面的状态为state
{
if ( pos == 0 ) return check(state);
if ( !flag && dp[pos][state]!=-1 ) return dp[pos][state];
int ed = flag?bit[pos]:9;
LL ans = 0;
rep(i,0,ed)
{
if ( i == 0 && !state )
ans+=dfs( pos - 1 , 0 , flag && i == ed );
else
ans+=dfs( pos - 1 , newstate(state,i) , flag && i == ed  );
}
if ( !flag ) dp[pos][state] = ans;
return ans;
}

LL cal(LL x)
{
int len = 0;
while(x)
{
bit[++len] = x % 10;
x /= 10;
}
return dfs( len , 0 ,1 );
}

void init()
{
int temp,t;
Clean(f,0);
Clean(dp,-1);
tree_pow[0] = 1;
rep(i,1,10) tree_pow[i] = 3 * tree_pow[i-1];
rep(i,1,tree_pow[10]-1)
{
temp = i;
Rrep(j,9,0)
if ( temp >= tree_pow[j] )
{
f[i][j] = t = temp/tree_pow[j];
temp-=t*tree_pow[j];
}
}
}

int main()
{
init();
int T;
cin>>T;
while(T--)
{
scanf("%lld %lld",&L,&R);
printf("%lld\n",cal(R)-cal(L-1));
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: