标签:typedef inline def cpp blank lse ble else printf
数位dp
#include<cstdio> #include<algorithm> using namespace std;const int N=60;const int M=250;typedef long long ll; ll dp[N][M][M][2];int a[N];ll l;ll r;int n;int jz;ll f[N][2];ll sum[N][2]; inline ll solve(ll x) { ll ret=0;n=0;while(x)a[++n]=x%jz,x/=jz;reverse(a+1,a+n+1);f[0][1]=1; for(int i=0;i<n;i++) { f[i+1][1]+=f[i][1];sum[i+1][1]+=sum[i][1]+f[i][1]*a[i+1]*i; for(int t=0;t<a[i+1];t++)f[i+1][0]+=f[i][1],sum[i+1][0]+=sum[i][1]+f[i][1]*t*i; for(int t=0;t<jz;t++)f[i+1][0]+=f[i][0],sum[i+1][0]+=sum[i][0]+f[i][0]*t*i; }ret=sum[n][0]+sum[n][1]; for(int i=0;i<=n;i++)sum[i][0]=sum[i][1]=0;for(int i=1;i<=n;i++)f[i][0]=f[i][1]=0; for(int nl=1;nl<n;nl++) { dp[0][0][0][1]=1; for(int i=0;i<n;i++) if(i+1<=nl) { for(int j=0;j<=i*jz;j++) { if(dp[i][j][j]==0)continue; dp[i+1][j+a[i+1]][j+a[i+1]][1]+=dp[i][j][j][1]; for(int t=0;t<a[i+1];t++)dp[i+1][j+t][j+t][0]+=dp[i][j][j][1]; for(int t=0;t<jz;t++)dp[i+1][j+t][j+t][0]+=dp[i][j][j][0]; } } else { for(int j=0;j<=i*jz;j++) for(int k=0;k<=nl*jz;k++) { if(dp[i][j][k]==0)continue; dp[i+1][j+a[i+1]][k][1]+=dp[i][j][k][1]; for(int t=0;t<a[i+1];t++)dp[i+1][j+t][k][0]+=dp[i][j][k][1]; for(int t=0;t<jz;t++)dp[i+1][j+t][k][0]+=dp[i][j][k][0]; } } for(int pre=0;pre<=nl*jz;pre++) for(int suf=pre+1;suf+pre<=n*jz;suf++) ret-=(suf-pre)*(dp[n][suf+pre][pre][0]+dp[n][suf+pre][pre][1]); for(int i=0;i<=n;i++) for(int j=0;j<=i*jz;j++) for(int k=0;k<=nl*jz;k++)dp[i][j][k][0]=dp[i][j][k][1]=0; }return ret; } int main(){scanf("%lld%lld%d",&l,&r,&jz);printf("%lld",solve(r)-solve(l-1));return 0;}
标签:typedef inline def cpp blank lse ble else printf
原文地址:https://www.cnblogs.com/ainiyuling/p/11249990.html