M - 上帝造题的八分钟(数位dp,dfs—dp,****)

区间内fufu数个数的数位dp解法

链接:登录—专业IT笔试面试备考平台_牛客网
来源:牛客网
 

我们称一个数为 fufu 数,当且仅当一个数满足下述性质:它的数位中有至少 3 个相邻的数字 3,且数字 0 的个数与数字 1 的个数相差至少为 1 的正整数。

给定一个区间 [l,r],你需要求出区间内的 fufu 数的个数。

答案对 10^9+7 取模。

输入描述:

输入一行,包括两个正整数 l,r(1≤l≤r≤10^100),表示你要查找的区间。

输出描述:

输出一行,一个正整数,表示区间内满足题目所描述性质的数量。

答案对 10^9 +7 取模。

示例1

输入

1 500

输出

0

说明

显然在 [1,500] 内没有 fufu 数。

示例2

输入

1333 1333

输出

1

说明

1333 中有 3 个相邻的数字 3,数字 0 的个数为 0,数字 1 的个数为 1,满足 fufu 数的性质。

示例3

输入

1 20000

输出

20

解析:

这道题显然是一道数位dp题。

f[pos][cp][pre1][pre2][limit][n3][last] 表示:

从高位往低位看,第pos位,0和1的个数差为cp,前一位为pre1,前二位为pre2,上一位是否为最大值,是否含有3个连续的3,当前一位是0还是1。

#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>
#include<sstream>
#include<deque>
#include<unordered_map>
#include<unordered_set>
#include<bitset>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<long long, long long> PLL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
const int INF = 0x3f3f3f3f;
const LL Mod = 1e9 + 7;
const int N = 100 + 10, M = 4e5 + 10, P = 110;
string l, r;
LL f[105][205][11][11][2][2][2];

LL dp(int pos, int cp, int pre1, int pre2, int limit, int n3, int last,vector<int>&num) {
	LL ret = 0;
	if (pos == -1)
		return n3 && (abs(cp - 100) >= 1);
	if (f[pos][cp][pre1][pre2][limit][n3][last])return f[pos][cp][pre1][pre2][limit][n3][last];
	int up = limit ? num[pos] : 9;
	for (int i = 0; i <= up; i++) {
		if (last && i == 0) {
			ret += dp(pos - 1, cp, i, pre1, limit && (i == up), n3, 1, num);
		}
		else {
			ret += dp(pos - 1, cp + (i == 0) - (i == 1), i, pre1, limit && (i == up), n3 | (pre1 == 3 && pre2 == 3 && i == 3), 0, num);
		}
		ret %= Mod;
	}
	return f[pos][cp][pre1][pre2][limit][n3][last] = ret;
}

LL work(vector<int>num) {
	memset(f, 0, sizeof f);
	return dp(num.size()-1, 100, 0, 0, 1, 0, 1,num);
}

bool check(vector<int>num) {
	int n1 = 0, n0 = 0;
	for (int i = 0; i < num.size(); i++) {
		if (num[i] == 1)n1++;
		else if (num[i] == 0)n0++;
	}
	if (!abs(n1 - n0))return 0;
	int n3 = 0;
	for (int i = 0; i < num.size(); i++) {
		if (num[i] == 3) {
			n3++;
			if (n3 == 3)return 1;
		}
		else {
			n3 = 0;
		}
	}
	return 0;
}

int main() {
	vector<int>L, R;
	cin >> l >> r;
	for (int i = 0; i < l.size(); i++) {
		L.push_back(l[i] - '0');
	}
	for (int i = 0; i < r.size(); i++) {
		R.push_back(r[i] - '0');
	}
	reverse(L.begin(), L.end());
	reverse(R.begin(), R.end());
	//cout << "___________________" << check(L) << endl;
	LL ans = (((work(R) - work(L)) % Mod + check(L)) %Mod+ Mod) % Mod;
	cout << ans << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值