UESTC-250-數位dp

題目大意:求一個區間內有多少個數中相鄰數位之差大於等於2;

題目解析::dp的第二維保存上一個數是多少,注意要處理前導零;

AC代碼:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
typedef long long ll;
ll dp[20][12];
int num[20];
int ab(int x,int y)
{
	if(x>y)	return x-y;
	return y-x;
}
ll dfs(int pos,int pre,bool lead,bool limit)
{
	if(pos==-1)	return 1;
	if(!lead&&!limit&&dp[pos][pre]!=-1)	return dp[pos][pre];
	int u=limit?num[pos]:9;
	ll ans=0;
	for(int i=0;i<=u;i++)
	{
		if(lead&&i==0)	ans+=dfs(pos-1,-4,lead&&i==0,limit&&i==u);
		else if(ab(i,pre)>=2)	ans+=dfs(pos-1,i,lead&&i==0,limit&&i==u); 
	}
	if(!lead&&!limit)	return dp[pos][pre]=ans;
	return ans;
}
ll solve(ll n)
{
	ll cnt=0;
	while(n)
	{
		num[cnt++]=n%10;
		n/=10;
	}
	return dfs(cnt-1,-4,true,true);
}
int main()
{
	ll a,b;
	memset(dp,-1,sizeof(dp));
	while(scanf("%lld%lld",&a,&b)!=EOF)
	{
		printf("%lld\n",solve(b)-solve(a-1));			
	}
	return 0;
}



發佈了193 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章