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)。、
最后处理完所有数位判断一下这个状态是不是满足题意。
[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; }
相关文章推荐
- CocoaPods的安装使用和常见问题
- encode与decode
- luajit 安装cjson
- xinit启动X Window System过程初探
- npm install -g ios-deploy 失败问题的解决方法
- 安卓快速实现关键字变色,搜索字变红,点击字体打电话,textview斜体,电商价格删除线,绿色下划线,图片(表情,图文混排) textview超链接跳转
- 【转】Android tools:context
- 电子大讲堂| 这些关于四轴飞行器名词你都明白么?
- hdu 1078 FatMouse and Cheese【经典记忆化搜索】
- java.lang.IllegalArgumentException: Mapped Statements collection does not contain value forCommand.c
- iOS开发之--- NSURLProtocol
- DLL注入之Appinit_Dlls
- 修改用户账户名称
- swift初始化函数失败
- 正则表达式
- centos安装epel源
- xib创建 图片还有label 赋不上值
- 客户同步的脚本
- redis 认识
- 蓝桥杯 PREV-9 大臣的旅费