【模拟】Permute Digits—CF915C

Permute Digits—CF915C

这个题的标签是 d p dp dp g r e e d y greedy greedy,但我觉得这更像一个模拟。

思路

  • 我们将最终答案的 数字 a 数字a 数字a 记为 r e s res res
    那么根据题目要求, r e s res res 可以分为3部分。
    左边的第一部分,每一位都与 数字 b 数字b 数字b 中对应的位上的数字相等。
    中间的第二部分,只有一个数字,这个数字严格小于 数字 b 数字b 数字b 中对应的位上的数字。
    右边的第三部分,直接将当前 数字 a 数字a 数字a 中剩余的没有填充过的数字从大到小排列即可。

例如

b:  27619361 9 183618162
res:27619361 8 987554432
三部分就是这样的。

C o d e Code Code

#include <bits/stdc++.h>
#define int long long
#define sz(a) ((int)a.size())
using namespace std;
using PII = pair<int, int>;
const int N = 2e5 + 10;
 
string sa, sb;
int numb_b; // 10进制数字b
int a[10]; // a[4]表示数字a中4的个数
int output; // 输出的答案
 
void func(int small) {
	// 复制a[]数组
	int a_copy[10];
	for (int i = 0; i <= 9; i ++) {
		a_copy[i] = a[i];
	}
	
	int res = 0;
	// 第一部分:每一位都和b中对于的数字相等
	for (int i = 0; i <= small - 1; i ++) {
		int now_b = sb[i] - '0';
		if (a_copy[now_b]) {
			a_copy[now_b] --;
			res = res * 10 + now_b;
		} else { // 如果不能实现,直接return
			return;
		}
	}
	
	int ok = 0; // 第二部分是否满足要求
	if (small >= 0 && small <= sz(sb) - 1) {
		/* 
		  找到第一个小于sb[small] - '0'的数字,
		  如果这个数字不存在则OK = 0,
		  即第二部分存在但没有满足条件的数字
		 */
		for (int i = sb[small] - '0' - 1; i >= 0; i --) {
			if (a_copy[i]) {
				a_copy[i] --;
				res = res * 10 + i;
				ok = 1;
				break;
			}
		}
	} else {
		ok = 1; // 如果第二部分不存在,则OK = 1
	}
	
	if (ok) {
		// 第三部分,从大到小填充数字a中的剩余位数即可
		for (int i = 9; i >= 0; i --) {
			while (a_copy[i] > 0) {
				if (1.0 * res * 10 + i > numb_b) {
					return;
				}
				res = res * 10 + i;
				a_copy[i] --;
			}
		}
		if (res <= numb_b) { // 如果 新产生的a <= 数组b 
			output = max(output, res);
		}
	}
}
 
void solve() {
	// 读入+预处理
	cin >> sa >> sb;
	for (auto p : sb) {
		numb_b = numb_b * 10 + p - '0';
	}
	for (auto p : sa) {
		a[p - '0'] ++;
	}
	
	if (sz(sa) == sz(sb)) { // a和b位数相同
		for (int small = -1; small <= sz(sb); small ++) {
			func(small);
		}
		cout << output << "\n";
	} else { // 如果a的位数比b的位数少
		for (int i = 9; i >= 0; i --) {
			while (a[i] > 0) {
				a[i] --;
				cout << i;
			}
		}
	}
}
 
signed main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int t = 1;
//	cin >> t; cin.get();
	while (t --) solve();
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值