链接 :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;
}