跳到正文

题解

题解 P2657 【[SCOI2009]windy数】

逍遥天堂约 2 分钟
原文
文章信息与版本

文章信息

发布
2018年8月16日
收录
2026年7月29日
更新
2026年11月2日
篇幅
约 2 分钟
获赞
1
题目
P2657

版本

  1. v1当前

数位动态规划

C++
#include<bits/stdc++.h>
using namespace std;
int f[12][10]={0};
long long power[13];
void PreWork()
{
	int i,j,k;
	power[0]=1;
	for(i=1;i<=12;i++)power[i]=power[i-1]*10;
	for(i=0;i<=9;i++)f[1][i]=1;
	for(i=2;i<=11;i++)
	for(j=0;j<=9;j++)
	for(k=0;k<=9;k++)
	if(abs(j-k)>=2)f[i][j]+=f[i-1][k];
}
int Count(int x)
{
	int w=0,y,i,j,pre,ans=0;
	while(power[w]<=x)w++;
	for(i=1;i<w;i++)//不足w位的数严格小于n,全部加入答案 
	for(j=1;j<=9;j++)ans+=f[i][j];
	y=x/power[w-1];
	for(j=1;j<y;j++)ans+=f[w][j];
	pre=y;
	x%=power[w-1];
	for(i=w-1;i>=1;i--)//枚举我们所求的数字第一次小于n的那一位 
	{
		y=x/power[i-1];
		for(j=0;j<y;j++)
		if(abs(j-pre)>=2)ans+=f[i][j];
		if(abs(pre-y)<2)break;
		pre=y;
		x%=power[i-1];
	}
	return ans;
}
int main()
{
	int a,b;
	cin>>a>>b;
	PreWork();
	cout<<Count(b+1)-Count(a)<<endl;
	return 0;
}