codeforces 55D Beautiful numbers(数位dp)
来源:互联网 发布:java 全栈开发框架 编辑:程序博客网 时间:2024/06/10 19:03
题意:
求[l,r]区间内是beautiful number的数, beautiful number的定义是一个数对于自己每位非0的数取模都为0
解题思路:
看出是一个数位dp题不难。
这个题非常巧,首先判断对于每位上的数取模等于0实际上相当于判断对每位上的数字的lcm取模是否等于0.所以我们记录状态的时候只要记录每位数字的lcm就可以了。
然后在搜索的时候如何判断一个数最后对lcm取模是否为0非常重要,我一开始想的是每搜索一位数,就用当前位的数对当前的lcm去取一下模,比如26,搜索到十位的时候我就用20对当前的lcm2去一下模,记录下这个值,最后判断能否对最后的lcm取模,而这样做的话,26这个示例就过不了,因为20对2取模为0后,加上6对lcm6的取模为0,按这个做法应该是一个beautiful数了,但是实际上却不是。
看了网上的博客才知道这题需要往数学上想一想,先贴上博客吧
http://blog.csdn.net/to_be_better/article/details/50658392
考虑sum%(n*x)%x=sum%x;
而1到9的lcm2520一定是最后我们得到的lcm的倍数,所以我们可以套用公式sum%(2520)%lcm=sum%lcm,那么我们要记录的状态就是sum%2520,最后再判断是否能对lcm取模等于0即可
dp的状态应该为dp[pos][mod][lcm]。表示pos位前的数对2520取模为mod且pos位前的数的最小公倍数为lcm的状态有多少个数满足条件。
另外开两重的2520数组太大,对于记录lcm的数组我们可以优化,能整除2520的数只有48个,也就是lcm只有48个结果,这样可以2520减少 到48.
代码:
#include<bits/stdc++.h>using namespace std;long long dp[22][2600][55];int num[22];long long now;int divi[3000];void init(){ for(int i=1, j=0; i<=2520; i++) { if(2520%i==0){ divi[i]=j++; } else divi[i]=0; } return;}long long lcm(int x, int y){return x*y/__gcd(x,y);}int cal(long long x){ if(x==0)return 0;int i=0;while(x>0){ num[i++]=x%10; x/=10;} return i; }long long dfs(int pos, int ismax, int mod, int lc){ if(pos<0) { if(mod%lc==0)return 1; else return 0; } if(!ismax && dp[pos][mod][divi[lc]]>-1)return dp[pos][mod][divi[lc]]; int bound=ismax?num[pos]:9; long long res=0; int l; for(int i=0; i<=bound; i++) { l=i?lcm(lc,i):lc; res+=dfs(pos-1, ismax && i==bound, (mod*10+i)%2520, l); } if(!ismax)dp[pos][mod][divi[lc]]=res; return res;}int main(){ int len, t; init(); cin>>t;long long l, r, a, b; memset(dp, -1, sizeof dp); while(t--){ cin>>l>>r; len=cal(l-1); a=dfs(len-1, 1, 0, 1); len=cal(r); b=dfs(len-1, 1, 0, 1); printf("%lld\n", b-a);}}
- Codeforces 55D Beautiful numbers 数位dp
- Codeforces 55D Beautiful numbers --- 数位DP
- Codeforces 55D Beautiful numbers 数位dp
- 【codeforces】55D. Beautiful numbers 数位DP
- [CodeForces 55D] Beautiful numbers && 数位DP
- Codeforces 55D Beautiful numbers 数位DP
- 【数位DP】 Codeforces 55D Beautiful numbers
- codeforces 55D Beautiful numbers[数位dp]
- [Codeforces 55D]Beautiful numbers(数位DP)
- CodeForces 55D Beautiful numbers (数位DP)
- Codeforces 55D Beautiful numbers【数位dp】
- codeforces 55D. Beautiful numbers (数位dp)
- CodeForces 55D Beautiful numbers(数位dp)
- codeforces-55D-Beautiful numbers(数位DP)
- codeforces 55D Beautiful numbers 数位dp
- Codeforces 55D Beautiful numbers 数位DP
- CodeForces 55D Beautiful numbers 数位dp
- CodeForces 55D Beautiful numbers(数位dp)
- 最短路,网络流(HDU 5294,Tricks Device)
- Nginx+Tomcat配置集群session共享
- HDUoj Virtual Friends (并查集
- java实现一个简单的代理服务器
- stm32在keil5中新建工程[0]
- codeforces 55D Beautiful numbers(数位dp)
- 4.3考试解题报告
- 17.5读书季-开启
- ubuntu 常用命令
- Hibernate学习笔记之三
- 知识点4:接口与抽象类有何区别
- libcurl开源库在VS2010环境下编译配置详解
- 折腾 Windows 10 输入法增加/添加美式键盘
- 学习python总结(一)