C. Permute Digits(思维+模拟)

本文介绍了一个算法问题,即如何通过改变一个给定正整数的数字顺序来构造一个不超过另一个给定正整数的最大可能数值。该算法首先比较两个输入数字的位数,接着对数字进行排序,并通过交换和比较来确定最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C. Permute Digits
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given two positive integer numbers a and b. Permute (change order) of the digits of a to construct maximal number not exceeding b. No number in input and/or output can start with the digit 0.

It is allowed to leave a as it is.

Input

The first line contains integer a (1 ≤ a ≤ 1018). The second line contains integer b (1 ≤ b ≤ 1018). Numbers don't have leading zeroes. It is guaranteed that answer exists.

Output

Print the maximum possible number that is a permutation of digits of a and is not greater than b. The answer can't have any leading zeroes. It is guaranteed that the answer exists.

The number in the output should have exactly the same length as number a. It should be a permutation of digits of a.

Examples
input
123
222
output
213
input
3921
10000
output
9321
input
4940
5000
output
4940


思路:

首先求字符串长度,然后sort排序之后在进行相应的操作

代码:

#include <bits/stdc++.h>
#define maxn 10010
#define ll long long
#define inf 0x7f7f7f7f
using namespace std;
int main(){
	int x=0,y=0;
	string s1,s2;
	cin>>s1>>s2;
	x=s1.length();
	y=s2.length();
	sort(s1.begin(),s1.end());
	if(x<y){
		reverse(s1.begin(),s1.end());
		cout<<s1<<endl;
		return 0;
	}
	string temp;
	for(int i=0;i<x;i++)
	  for(int j=x-1;j>i;j--){
	  	temp=s1;
	  	swap(s1[i],s1[j]);
	  	sort(s1.begin()+i+1,s1.end());
	  	//cout<<s1<<endl;
	  	if(s1.compare(s2)>0){
	  		s1=temp;
	  		
		  }
		  else{
		  	break;
		  }
	  }
	  cout<<s1<<endl;
	  return 0; 
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值