lightoj 1205 數位dp

1205 - Palindromic Numbers
Time Limit: 2 second(s) Memory Limit: 32 MB

A palindromic number or numeral palindrome is a 'symmetrical' number like 16461 that remains the same when its digits are reversed. In this problem you will be given two integers i j, you have to find the number of palindromic numbers between i and j (inclusive).php

Input

Input starts with an integer T (≤ 200), denoting the number of test cases.ios

Each case starts with a line containing two integers i j (0 ≤ i, j ≤ 1017).git

Output

For each case, print the case number and the total number of palindromic numbers between i and (inclusive).數組

Sample Input

Output for Sample Input

4this

1 10spa

100 1code

1 1000orm

1 10000blog

Case 1: 9ci

Case 2: 18

Case 3: 108

Case 4: 198

 


PROBLEM SETTER: JANE ALAM JAN
題意:
求區間內迴文串數的個數
//開個數組存一下回文串,還要處理前導零。sta表示到目前爲止是否合法
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
int t,bit[20],num[20];
ll f[20][20][2],P,Q;
ll dfs(int pos,int s,int sta,bool limit)
{
    if(pos==0) return sta;
    if(!limit&&f[pos][s][sta]!=-1) return f[pos][s][sta];
    int max_b=(limit?bit[pos]:9);
    ll ans=0;
    for(int i=0;i<=max_b;i++){
        num[pos]=i;
        if(pos==s&&i==0)
            ans+=dfs(pos-1,s-1,sta,limit&&(i==max_b));
        else if(sta&&pos<=s/2)
            ans+=dfs(pos-1,s,num[s-pos+1]==i,limit&&(i==max_b));
        else ans+=dfs(pos-1,s,sta,limit&&(i==max_b));
    }
    if(!limit) f[pos][s][sta]=ans;
    return ans;
}
ll solve(ll x)
{
    if(x<0) return 0;
    int pos=0;
    while(x){
        bit[++pos]=x%10;
        x/=10;
    }
    return dfs(pos,pos,1,1);
}
int main()
{
    memset(f,-1,sizeof(f));
    scanf("%d",&t);
    for(int cas=1;cas<=t;cas++){
        scanf("%lld%lld",&P,&Q);
        if(P>Q) swap(P,Q);
        printf("Case %d: %lld\n",cas,solve(Q)-solve(P-1));
    }
    return 0;
}
相關文章
相關標籤/搜索