【数位dp】【回文】

这是一个关于寻找介于两个整数i和j(包括i和j)之间的回文数的问题。回文数是指正读反读都相同的数。输入包含T个测试用例,每个用例包含一对整数i和j。输出每个测试用例中回文数的数量。

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

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

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 (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




#include <iostream>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
using namespace std;
    
int T;
typedef long long ll;
int bits[20];
ll dp[20][20];

ll dfs(int len,int l,int r,bool flag,bool ok)
{
	if(r > l) return !flag || (flag && ok);
	if(!flag && ~dp[len][l])  return dp[len][l];
	int end = flag ? bits[l] : 9;
	ll res = 0;
	for(int i=0;i<=end;i++)
	{
		if(l == len && i == 0) continue;
		bool g = ok;
		if(ok) g = bits[r] >= i;
		else g = bits[r] > i;
		res += dfs(len,l-1,r+1,flag&&(i==end),g);
	}
	return flag ? res : dp[len][l] = res;

}


ll solve(ll x)
{
	if(x < 0) return 0;
	if(x == 0) return 1;
	ll tt = x;
	int cnt = 0;
	while(tt >0 )
	{
		bits[++cnt] = tt % 10;
		tt /= 10;
	}
	ll ret = 1;
	for(int i=cnt;i>=1;i--)
		ret += dfs(i,i,1,i==cnt,true);
	return ret;
}
int main()
{
	int C = 1;
    scanf("%d",&T);
	memset(dp,-1,sizeof(dp));
	while(T --)
	{
		ll l,r;
		scanf("%I64d%I64d",&l,&r);
		if(l > r) swap(l,r);
		printf("Case %d: %I64d\n",C++,solve(r)-solve(l-1));
	}
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值