HDU 3271 SNIBB(数位DP+构造)

思路:数位DP+构造,先dp[i][j]表示i位总和为j的情况数,然后两种情况分别去进行数位DP,按高位往低位放去构造即可

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int q, x, y, b, m, k;

int bit[35], bn, dp[35][305];

void get(int x) {
	bn = 0;
	if (!x) bit[bn++] = 0;
	while (x) {
		bit[bn++] = x % b;
		x /= b;
	}
}

int cal1(int x) {
	if (x == -1) return 0;
	get(x);
	int ans = 0, sum = m;
	for (int i = bn; i; i--) {
		for (int x = 0; x < bit[i - 1]; x++) {
			if (sum - x < 0) continue;
			ans += dp[i - 1][sum - x];
		}
		sum -= bit[i - 1];
		if (sum < 0) break;
	}
	return ans;
}

int cal2(int x) {
	int len = 0;
	while (dp[len][m] < x) len++;
	int ans = 0;
	for (int i = len; i; i--) {
		for (int j = 0; j < b; j++) {
			if (m - j < 0) break;
			if (dp[i - 1][m - j] >= x) {
				m -= j;
				ans = ans * b + j;
				break;
			}
			x -= dp[i - 1][m - j];
		}
	}
	return ans;
}

int main() {
	int cas = 0;
	while (~scanf("%d%d%d%d%d", &q, &x, &y, &b, &m)) {
		printf("Case %d:\n", ++cas);
		if (x > y) swap(x, y);
		memset(dp, 0, sizeof(dp));
		dp[0][0] = 1;
		for (int i = 0; i < 33; i++) {
			for (int j = 0; j <= m; j++) {
				if (!dp[i][j]) continue;
				for (int x = 0; x < b; x++) {
					if (j + x > 300) continue;
					dp[i + 1][j + x] += dp[i][j];
				}
			}
		}
		if (q == 1) printf("%d\n", cal1(y + 1) - cal1(x));
		else {
			scanf("%d", &k);
			int a = cal1(x);
			if (cal1(y + 1) - a < k) printf("Could not find the Number!\n");
			else printf("%d\n", cal2(k + a));
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值