跳到正文

题解

P11557 [ROIR 2016] 有趣数字 (Day 2) 题解

_SLIDE_约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年1月27日
收录
2026年6月4日
更新
2026年10月22日
篇幅
约 4 分钟
获赞
5
题目
P11557

版本

  1. v1当前

温馨提示:在专栏食用效果更佳。

记忆化搜索,数位 DP。

设有一自然数 n\text{n},记 n\text{n} 的第 p\text{p} 位为 np(p≥1)\text{n}_\text{p}(\text{p}\ge1)。定义 dpp,e,last\text{dp}_\text{p,e,last} 表示以当前数为前缀的数中“有趣的”数的个数。其中:

  • p\text{p} 表示当前搜索到了第 p\text{p} 位,p∈[1,log⁡10n]∩Z\text{p}\in[1,\log_{10}\text{n}]\cap\Z;
  • e\text{e} 表示当前的数是否卡了 n\text{n} 上限,e∈[0,1]∩Z\text{e}\in[0,1]\cap\Z;
  • last\text{last} 表示上一位的数值,last∈[0,9]∩Z\text{last}\in[0,9]\cap\Z。

状态转移:dpp,e,last=∑i=last9dpp+1,i=np∧e,i\text{dp}_\text{p,e,last}=\sum\limits_\text{i=last}^9 \text{dp}_{\text{p+1},\text{i}=\text{n}_\text{p}\wedge\text{e},i}。

设 f(n)=∑e∈[0,1]∩Z,last∈[0,9]∩Zdp⌊log⁡10n⌋,e,last\text{f}(\text{n})=\sum\limits_{\text{e}\in[0,1]\cap\Z,\text{last}\in[0,9]\cap\Z}\text{dp}_{\left\lfloor\log_{10}\text{n}\right\rfloor,\text{e},\text{last}},\\ 则答案为 (f(R)−f(L−1)) mod (109+7)(\text{f}(\text{R})-\text{f}(\text{L}-1))\bmod(10^9+7)。

Code

C++
#include <iostream>
#include <algorithm>
#include <vector>
#define ll long long
using namespace std;
int x,len,s[101],dp[101][2][10];
int dfs(const int p,const int e,const int last=0) { // 求 dp
	if(p==len) return 1;
	else if(dp[p][e][last]>=0) return dp[p][e][last];
	ll ret=0;
	for(int i=last;i<10;i++)
		if(e&&i>s[p]) break;
		else ret+=dfs(p+1,e&(i==s[p]),i);
	return dp[p][e][last]=ret%1000000007;
}
ll solve(const string &n) { // 求 M
	if(n=="0") return 1;
	len=n.size();
	for(int i=0;i<len;i++)
		s[i]=n[i]-'0';
	for(auto &i: dp)
		for(auto &j: i)
			for(auto &k: j)
				k=-1;
	return dfs(0,1);
}
string sub1(string s) { // 高精度字符串减1
	if(s=="1") return "0";
	vector<int> v;
	for(char c: s)
		v.push_back(c-'0');
	reverse(v.begin(),v.end());
	v[0]--;
	for(size_t i=0;i+1<v.size();i++)
		if(v[i]<0) v[i]+=10,v[i+1]--;
	while(!v[v.size()-1])
		v.pop_back();
	reverse(v.begin(),v.end());
	s="";
	for(size_t i=0;i<v.size();i++)
		s+=char(v[i]+48);
	return s;
}
int main() {
	cin.tie(nullptr)->sync_with_stdio(false),
	cout.tie(nullptr);
	string l,r;
	cin>>l>>r;
	cout<<(solve(r)-solve(sub1(l))+1000000007)%1000000007;
	return 0;
}
原文
存档评论1 条抓取于