codeforces 55d 数位dp(整除问题)

Beautiful numbers

题意:求l r区间多少个数满足能整除数位上面所有的数(不包括0)

思路:数位dp,看到这个首先想到的是枚举模数,因为1-9 9个数的lcm只有2520,而且只有48个因子,dp[pos][v][now][mod],mod表示枚举的模数,v表示当前位%mod的值(这里有疑问的可以先看一下bzoj1799),now表示当前位出现的数的lcm,最后v==0&&now==mod的时候表示可行,但是内存一直超,即使把now和mod2维hash一下优化到48*48,内存也要900m,如果把mod一维去掉的话,每次枚举mod的时候都要初始化dp,显然会超时。这里可以固定mod,而不是枚举,固定mod为2520,即1-9的lcm,每次只保留当前数模mod的值,最后判断v%now==0即表示可行,因为mod很小,所以保证了时间和空间上都可以过去,这里可以固定mod的原因是,now一定是mod的因子,也就是说,所以最后的余数是不会影响这个数是不是now的倍数

AC代码:

#include "iostream"
#include "iomanip"
#include "string.h"
#include "stack"
#include "queue"
#include "string"
#include "vector"
#include "set"
#include "map"
#include "algorithm"
#include "stdio.h"
#include "math.h"
#pragma comment(linker, "/STACK:102400000,102400000")
#define bug(x) cout<<x<<" "<<"UUUUU"<<endl;
#define mem(a,x) memset(a,x,sizeof(a))
#define step(x) fixed<< setprecision(x)<<
#define mp(x,y) make_pair(x,y)
#define pb(x) push_back(x)
#define ll long long
#define endl ("\n")
#define ft first
#define sd second
#define lrt (rt<<1)
#define rrt (rt<<1|1)
using namespace std;
const ll mod=2520;
const ll INF = 1e18+1LL;
const int inf = 1e9+1e8;
const double PI=acos(-1.0);
const int N=1e5+1000;

ll dp[20][2520][48];
int bit[20],has[3000];

ll dfs(int limit, int pos, int v, int now){
    if(pos==-1) return now==0||v%now==0;//now为0的话即表示当前的数为00000,可判可不判,因为数据范围为1-int64
    if(!limit && dp[pos][v][has[now]]!=-1) return dp[pos][v][has[now]];
    int up=limit?bit[pos]:9;
    ll ans=0;
    for(int i=0; i<=up; ++i){
        int k=i?i:1;
        ans+=dfs(limit&&i==bit[pos], pos-1, (v*10+i)%mod, now*k/__gcd(now,k));
    }
    if(!limit) dp[pos][v][has[now]]=ans;
    return ans;
}

ll solve(ll x){
    int p=0; ll ans=0;
    while(x>0){
        bit[p++]=x%10;
        x/=10;
    }
    return dfs(1,p-1,0,1);
}

int main(){
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    int T,cnt=0; mem(has,-1);
    for(int i=0; i<(1<<8); ++i){
        int mod=1;
        for(int j=i,o=2; j>0; j>>=1,++o){
            if(j&1) mod=mod*o/__gcd(mod,o);
        }
        if(has[mod]==-1){
            has[mod]=cnt++;
        }
    }
    cin>>T; mem(dp,-1);
    while(T--){
        ll l,r; cin>>l>>r;
        cout<<solve(r)-solve(l-1)<<endl;
    }
    return 0;
}

 

posted on 2017-10-19 20:20  lazzzy  阅读(211)  评论(0编辑  收藏  举报

导航