Palindromic Numbers LightOJ - 1205 数位dp 求回文数

传送门

文章目录

题意:

[ l , r ] [l,r] [l,r]中有多少个回文数。

思路:

裸的数位 d p dp dp啦,记 d p [ p o s ] [ p r e ] [ s t a t e ] dp[pos][pre][state] dp[pos][pre][state]表示到了第 p o s pos pos位,回文是从第 p r e pre pre位开始的,并且当前是否为回文串 s t a t e state state。这样就可以把要求的数字特征表示出来,让后还要记录一下选的数是多少,在 p o s < = ( p r e − 1 ) / 2 pos<=(pre-1)/2 pos<=(pre1)/2的时候就需要判断是否为回文串了。
好长时间没写数位 d p dp dp了, s o l v e solve solve传值的时候 L L LL LL传成了 i n t int int

//#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid (tr[u].l+tr[u].r>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std;

//void rd_cre() { freopen("d://dp//data.txt","w",stdout); srand(time(NULL)); }
//void rd_ac() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//AC.txt","w",stdout); }
//void rd_wa() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//WA.txt","w",stdout); }

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;

const int N=1010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;

LL l,r;
int a[N],num[N],tot;
LL f[30][30][2];

LL dfs(int pos,int pre,int state,int flag)
{
    
    
    if(pos==-1) return state;
    if(flag&&f[pos][pre][state]!=-1) return f[pos][pre][state];
    int x=flag? 9:a[pos];
    LL ans=0;
    for(int i=0;i<=x;i++)
    {
    
    
        num[pos]=i;
        if(i==0&&pos==pre) ans+=dfs(pos-1,pre-1,state,flag||i<x);
        else if(pos<=(pre-1)/2&&state) ans+=dfs(pos-1,pre,state&&(num[pre-pos]==i),flag||i<x);
        else ans+=dfs(pos-1,pre,state,flag||i<x);
    }
    if(flag) f[pos][pre][state]=ans;
    return ans;
}

LL solve(LL x)
{
    
    
    tot=0;
    if(x<0) return 0;
    if(x==0) return 1;
    while(x)
    {
    
    
        a[tot++]=x%10;
        x/=10;
    }
    return dfs(tot-1,tot-1,1,0);
}

int main()
{
    
    
//	ios::sync_with_stdio(false);
//	cin.tie(0);

    memset(f,-1,sizeof(f));
    int _; scanf("%d",&_);
    for(int __=1;__<=_;__++)
    {
    
    
        scanf("%lld%lld",&l,&r);
        if(l>r) swap(l,r);
        printf("Case %d: %lld\n",__,solve(r)-solve(l-1));
    }


	return 0;
}
/*

*/



猜你喜欢

转载自blog.csdn.net/m0_51068403/article/details/115159016