I - 吉哥系列故事――恨7不成妻 HDU - 4507
单身!
依然单身!
吉哥依然单身!
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 求模后输出。
题解: 定义一个结构体,维护三个数据,cnt指满足题意的数的个数,sum指满足题意的数的和,res指满足题意的数的平方和,dp[pos][sum1][sum2],和简单的数位dp一样,pos指位数,sum1指这个位数之前的每一位的和对10取余,sum2指之前的数的值对10取余。
重点就是如何维护结构体的三个数据了,设下一个状态为temp,现在的状态为now,cnt很简单,就是简单数位dp的维护,now.cnt+=temp.cnt;
sum的话,是temp.sum加上现在这个状态的数的贡献,设现在这个数为i,这个数的贡献为i*10^(pos-1)*temp.cnt,因为这个数会出现temp.cnt次,而且处在第pos位,这也是维护cnt的原因;
而维护sum的原因就是为了维护res,设下一个状态得到的数是x[1],x[2]....x[temp.cnt],而now.res=(i*10^(pos-1)+x[1])*(i*10^(pos-1)+x[1])+(i*10^(pos-1)+x[2])*(i*10^(pos-1)+x[2])+.....+(i*10^(pos-1)+x[temp.cnt])*(i*10^(pos-1)+x[temp.cnt]),这个数等于temp.cnt*i*10^(pos-1)*i*10^(pos-1)+2*i*10^(pos-1)*temp.sum+temp.res.
总结就是 now.cnt+=temp.cnt;
now.sum+=temp.sum+i*10^(pos-1)*temp.cnt;
now.res+=temp.cnt*i*10^(pos-1)*i*10^(pos-1)+2*i*10^(pos-1)*temp.sum+temp.res.
#include<stdio.h>
#include<string.h>
#define ll long long
#define mod 1000000007
struct node{
ll cnt,sum,res;
node(){cnt=-1;sum=0;res=0;}
node(ll a,ll b,ll c){cnt=a;sum=b;res=c;}
}dp[20][10][10];
ll digit[20];
ll s[20];
node dfs(int pos,int sum1,int sum2,int flag){
if(pos==0){
if(sum1==0||sum2==0)return node(0,0,0);
else return node(1,0,0);
}
if(flag==0&&dp[pos][sum1][sum2].cnt!=-1)return dp[pos][sum1][sum2];
ll maxn=9;
if(flag==1)maxn=digit[pos];
node ans;
ans.cnt=0;
for(ll i=0;i<=maxn;i++){
if(i==7)continue;
node temp=dfs(pos-1,(sum1+i)%7,(sum2*10+i)%7,flag&&(i==maxn));
ans.cnt+=temp.cnt;
ans.cnt=ans.cnt%mod;
ans.sum+=(temp.sum+i*s[pos-1]%mod*temp.cnt%mod)%mod;
ans.sum=ans.sum%mod;
ans.res+=(temp.res+(2*i%mod*s[pos-1]%mod)%mod*temp.sum)%mod;
ans.res=ans.res%mod;
ans.res+=(temp.cnt%mod*(i%mod*s[pos-1]%mod)%mod*(i%mod*s[pos-1]%mod)%mod)%mod;
ans.res=ans.res%mod;
}
if(flag==0)dp[pos][sum1][sum2]=ans;
return ans;
}
ll solve(ll n){
int pos=0;
while(n!=0){
digit[++pos]=n%10;
n=n/10;
}
node temp=dfs(pos,0,0,1);
return temp.res;
}
int main(){
int t;
scanf("%d",&t);
s[0]=1;
for(int i=1;i<=18;i++)s[i]=(10*s[i-1])%mod;
while(t--){
ll l,r;
scanf("%lld %lld",&l,&r);
printf("%lld\n",(solve(r)-solve(l-1)+mod)%mod);
}
}