Codeforces 205 C. Little Elephant and Interval (数位 dp)

本文介绍了一种使用数位DP算法解决特定数学问题的方法:计算指定区间内首尾数字相同的数的数量。通过详细解析算法思路和分享C++实现代码,帮助读者理解并掌握该算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接 :C. Little Elephant and Interval
题意:
求 l 到 r 区间内首尾和末位相同的数的个数。
思路:
写了个很莽的数位 dp ,貌似有其他更巧妙的方法,这里就是找到第一个不为 0 的数作为首位,最后判断最后一位和第一位是否相等并且这个数不能为 0 .
代码:

#include<iostream>
#include<cstdio>
#include<stack>
#include<math.h>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll ;
const int maxn=1e6+7;
ll dp[20][20][3],a[20],poss;
ll dfs(int pos,int fir,int pre,int limit,int sta){
    if(pos==-1) return fir == pre &&sta == 0;

    if(!limit&&fir!=-1&&dp[pos][fir][sta]!=-1) return dp[pos][fir][sta];

    int up=limit ? a[pos] : 9;
    ll tmp=0;
    for(int i=0; i <= up; i++){
        if(sta && i != 0) fir = i;
        tmp += dfs(pos-1,fir,i,limit &&(i == a[pos]),sta && i == 0);
    }
    if(!limit&&fir!=-1) dp[pos][fir][sta]=tmp;
    return tmp;
}
ll solve(ll x){
     int pos=0;
     while(x>0){
         a[pos++]=x%10;
         x/=10;
     }
     poss = pos - 1;
     return dfs(pos-1,-1,-1,1,1);
}
int main(){
    memset(dp,-1,sizeof(dp));
    ll a,b;
    cin>>a>>b;
    cout<<solve(b) -solve(a-1) <<endl;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值