程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LightOJ-1205 - Palindromic Numbers

LightOJ-1205 - Palindromic Numbers

編輯:C++入門知識

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).

Input

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

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

Output

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

Sample Input

Output for Sample Input

4

1 10

100 1

1 1000

1 10000

Case 1: 9

Case 2: 18

Case 3: 108

Case 4: 198



題目大意為:a-b區間有多少個數是回文數,a,b的范圍 為10^17

因此只能用數位DP


用DP[pos][len] 記錄答案 pos表示的是當前的位置,len為回文數長度

用num[pos] 記錄前mid位的信息


#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
ll a,b;
vector digit;
int num[20];
ll dp[19][19];
ll dfs(int pos,int len,int zero,int done){
    if(pos==-1) return 1;
    if(!done && !zero && ~dp[pos][len]) return dp[pos][len];
    ll res = 0;
    int end = done?digit[pos]:9;
    for(int i = 0; i <= end; i++){
        if(zero){
            num[len] = i;
            res += dfs(pos-1,len-!i,zero&&i==0,done&&i==end);
        }else{
            int mid = (len+1)>>1;
            if(len&1){
                if(pos < mid){
                    if(num[2*mid-pos-1]==i)
                        res += dfs(pos-1,len,zero&&i==0,done&&i==end);
                }else{
                    num[pos] = i;
                    res += dfs(pos-1,len,zero&&i==0,done&&i==end);
                }
            }else{
                if(pos == mid){
                        res +=  dfs(pos-1,len,zero&&i==0,done&&i==end);
                }else if(pos < mid){
                    if(num[mid*2-pos]==i)
                        res +=  dfs(pos-1,len,zero&&i==0,done&&i==end);
                }
                else{
                    num[pos] = i;
                    res += dfs(pos-1,len,zero&&i==0,done&&i==end);
                }
            }
        }
    }
    if(!done && !zero) dp[pos][len] = res;
    return res;

}
ll solve(ll x){
    digit.clear();
    memset(dp,-1,sizeof dp);
    if(x==0) digit.push_back(0);
    while(x){
        digit.push_back(x%10);
        x /= 10;
    }
    return dfs(digit.size()-1,digit.size()-1,1,1);
}
int main(){
    int ncase,T=1;
    cin >> ncase;
    while(ncase--){
        cin >> a >> b;
        if(a > b) swap(a,b);
        printf("Case %d: %lld\n",T++,solve(b)-solve(a-1));
        //cout<<<


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved