您的位置:首页 > 其它

HDU - 4507 吉哥系列故事——恨7不成妻 (数位DP&记忆化dfs)好题

2016-05-17 15:33 591 查看
HDU - 4507
吉哥系列故事——恨7不成妻

Time Limit:                                                        500MS                        Memory Limit:                                                        32768KB                        64bit IO Format:                            %I64d & %I64u                       
SubmitStatus

Description

  单身!       

  依然单身!       

  吉哥依然单身!       

  DS级码农吉哥依然单身!       

  所以,他生平最恨情人节,不管是214还是77,他都讨厌!       

         

  吉哥观察了214和77这两个数,发现:       

  2+1+4=7

  7+7=7*2

  77=7*11

  最终,他发现原来这一切归根到底都是因为和7有关!所以,他现在甚至讨厌一切和7有关的数!       

  什么样的数和7有关呢?       

  如果一个整数符合下面3个条件之一,那么我们就说这个整数和7有关——       

  1、整数中某一位是7;       

  2、整数的每一位加起来的和是7的整数倍;       

  3、这个整数是7的整数倍;       

  现在问题来了:吉哥想知道在一定区间内和7无关的数字的平方和。       

       

Input

输入数据的第一行是case数T(1 <= T <= 50),然后接下来的T行表示T个case;每个case在一行内包含两个正整数L, R(1 <= L <= R <= 10^18)。       

       

Output

请计算[L,R]中和7无关的数字的平方和,并将结果对10^9 + 7 求模后输出。      
       

Sample Input

3
1 9
10 11
17 17

               

Sample Output

236
221
0

               

Hint

Source
2013腾讯编程马拉松初赛第一场(3月21日)
//思路:
看大神的,太牛啦。。。

设后i-1位合法的数字有N个,num1, num2, num3, num4...numN考虑第i位的x,则num = 10^(i-1) * x。

和为num * N +(num1 + ... + numN)。

平方和为(num + num1)^2 + (num + num2) ^ 2 + (num + num3) ^ 2 + ... + (num + numN) ^ 2。  

化简后 = N * num^2 + 2 * num * (num1+...+numN) + (num1^2 + ... + numN^2)。

用dp维护个数cnt,和sum1, 平方和sum2即可。

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#define ll long long
#define M 1000000007
using namespace std;
struct zz
{
ll cnt;
ll sum1;
ll sum2;
}dp[30][7][7];
int bit[30];
ll p[30];
void init()
{
memset(dp,-1,sizeof(dp));
p[0]=1ll;
for(int i=1;i<20;i++)
{
p[i]=p[i-1]*10%M;
}
}
void add(ll &x,ll y)
{
x+=y;
x%=M;
}
ll Fac(ll x)
{
return x*x%M;
}
zz dfs(int pos,int presum,int preyu,bool yes)
{
if(pos==-1)
{
zz tmp;
tmp.cnt=(presum&&preyu);
tmp.sum1=tmp.sum2=0ll;
return tmp;
}
if(!yes&&dp[pos][presum][preyu].cnt!=-1)
return dp[pos][presum][preyu];
zz ans,tmp;
ans.cnt=ans.sum1=ans.sum2=0ll;
int end=yes?bit[pos]:9;
for(int i=0;i<=end;i++)
{
if(i==7) continue;
tmp=dfs(pos-1,(presum+i)%7,(preyu*10+i)%7,yes&&i==end);
add(ans.cnt,tmp.cnt);
add(ans.sum1,(tmp.sum1+tmp.cnt*p[pos]%M*i%M)%M);
add(ans.sum2,((tmp.cnt*Fac(p[pos])%M*Fac(i)%M+tmp.sum2)%M+tmp.sum1*2%M*p[pos]%M*i%M)%M);
}
if(!yes)
dp[pos][presum][preyu]=ans;
return ans;
}
ll count(ll n)
{
int len=0;
while(n)
{
bit[len++]=n%10;
n/=10;
}
return dfs(len-1,0,0,1).sum2;
}
int main()
{
init();
int t;
scanf("%d",&t);
while(t--)
{
ll n,m;
scanf("%lld%lld",&n,&m);
printf("%lld\n",((count(m)-count(n-1))%M+M)%M);
}
return 0;
}


 

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