CodeForces 95 D.Horse Races(数位DP)

Description

定义伪幸运数字为该数字中有距离不超过 k 位的两位上都是 4 7 ,问区间 [ L , R ] 中伪幸运数字的个数

Input

第一行输入两个整数 T , k ,其中 T 表示用例组数,之后 T 行每行输入两个整数 L i , R i 表示一组查询

( 1 t , k 1000 , 1 L i R i 10 1000 )

Output

对于每组查询,输出该区间中伪幸运数字的个数

Sample Input

1 2
1 100

Sample Output

4

扫描二维码关注公众号,回复: 2189367 查看本文章

Solution

数位 D P ,记录之前是否出现过 4 , 7 以及记录当前位与之前出现的最近的 4 , 7 的距离即可

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=1005;
#define mod 1000000007
int T,n,k,dp[maxn][maxn][2],a[maxn];
char s[maxn];
int dfs(int pos,int dis,int flag,int fp)
{
    if(!pos)return flag;
    if(!fp&&dp[pos][dis][flag]!=-1)return dp[pos][dis][flag];
    int ans=0,fpmax=fp?a[pos]:9;
    for(int i=0;i<=fpmax;i++)
        if(i!=4&&i!=7)ans=(ans+dfs(pos-1,max(0,dis-1),flag,fp&&i==fpmax))%mod;
        else ans=(ans+dfs(pos-1,k,flag||dis,fp&&i==fpmax))%mod;
    if(!fp)dp[pos][dis][flag]=ans;
    return ans;
}
int check()
{
    int pre=-1;
    for(int i=0;i<n;i++)
        if(s[i]=='4'||s[i]=='7')
        {
            if(pre!=-1&&i-pre<=k)return 1;
            pre=i;
        }
    return 0;
}
int main()
{
    scanf("%d%d",&T,&k);
    memset(dp,-1,sizeof(dp));
    while(T--)
    {
        scanf("%s",s);
        n=strlen(s);
        for(int i=1;i<=n;i++)a[i]=s[n-i]-'0';
        int ans=(dfs(n,0,0,1)-check()+mod)%mod;
        scanf("%s",s);
        n=strlen(s);
        for(int i=1;i<=n;i++)a[i]=s[n-i]-'0';
        ans=(dfs(n,0,0,1)-ans+mod)%mod;
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/V5ZSQ/article/details/81063490