LightOJ 1205

关键维护三个变量start,dex,flag,分别代表开始位,当前位,开始位到当前位是否回文。
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include   
#include   
#include   
#include   
#include 
#include   
#include 
#include  
#include 
#include 
#include 
#include 
#include 
#include 
#define INF 0x3f3f3f3f
#define LL long long
#define fora(i,a,n) for(int i=a;i<=n;i++)
#define fors(i,n,a) for(int i=n;i>=a;i--)
#define sci(x) scanf("%d",&x);
#define scl(x) scanf("%lld",&x);
#define MAXN 100024
const double eps = 1e-8;
using namespace std;
LL t, l, r, k, z = 1;
LL dp[22][22][2], digits[22], num[22];
LL dfs(LL start, LL dex, LL flag, LL p) {
	LL sum = 0;
	if (dex == 0) return flag;
	if (dp[start][dex][flag]!=-1 && !p) return dp[start][dex][flag];
	LL u = p ? digits[dex] : 9;
	fora(i, 0, u) {
		num[dex] = i;
		if (start == dex&&i == 0) //前缀全为0
			sum += dfs(start - 1, dex - 1, flag, p&&i == u);
		else if (flag && (start /2+1)> dex) //回文串的后半部分,也就是需要判断是否回文的部分
			sum += dfs(start, dex - 1, num[start - dex+1] == i, p&&i == u);
		else sum += dfs(start, dex - 1, flag, p&&i == u); //回文串的前半部分
	}
	if(!p) dp[start][dex][flag] = sum;
	return  sum;
}
LL digit(LL n) {
	
	if (n == 0)  return 1;
	if (n<0) return 0;
	k = 0;
	while (n) {
		digits[++k] = n % 10;
		n /= 10;
	}
	return dfs(k, k, 1, 1);
}
int main() {
#ifdef DID
	freopen("in.txt", "r", stdin);
	//freopen("out.txt","w",stdout);
#endif
	scl(t);
	memset(dp, -1, sizeof(dp));
	while (t--) {
		scl(l); scl(r);
		if (l>r) swap(l, r);
		LL sum1 = digit(r);
		LL sum2 = digit(l - 1);

		printf("Case %d: ", z++);
		printf("%lld\n", sum1 - sum2);
	}
	return 0;
}

你可能感兴趣的:(C++,C,数位DP)