The Next Permutation C++

题目描述

For this problem, you will write a program that takes a (possibly long) string of decimal digits, and outputs the permutation of those decimal digits that has the next larger value (as a decimal number) than the input number. For example: 123 -> 132 279134399742 - 279134423799 It is possible that no permutation of the input digits has a larger value. For example, 987.

输入格式:

The first line of input contains a single integer P, (1 ≤ P ≤ 1000), which is the number of data sets that follow. Each data set is a single line that contains the data set number, followed by a space, followed by up to 80 decimal digits which is the input value.

输出格式:

For each data set there is one line of output. If there is no larger permutation of the input digits, the output should be the data set number followed by a single space, followed by the string BIGGEST. If there is a solution, the output should be the data set number, a single space and the next larger permutation of the input digits.

输入样例

3
1 123
2 279134399742
3 987

输出样例

1 132
2 279134423799
3 BIGGEST

这道题的意思就是说给你一个字符串数字x,能否将数字位置交换得到一个最小且大于x的字符串数字y,然后输出序号+得到的字符串数字y
这道题的解法其实可以先思考一下,要想得到一个最小的字符串数字,则要找一个数从左往右最靠右侧较小的数字和从右侧开始数大于该数的数字进行交换,279134399742像这个例子,从左往右可以发现3和从右往左的4进行交换,交换后得到279134499732,此时必然是大于原先的字符串数字,但是要想得到最小的字符串数字,则要将279134499732中4的右侧数的小数放在前面,利用递归进行循环可以进行交换,我比较喜欢c++里的string做这道题。
然后这个题理解一下其实不难,当然感觉学校的oj测试用例有些弱,不知道遇到大数的时候这个递归会不会死掉,当然题目说最多只有80个字符数字,那其实问题不大,AC了就行。

#include<iostream>
#include<algorithm>
#include<cstring>
#include<stdio.h>
#include<cmath>
using namespace std;
string line;
void dfs(int left){
	if(left>=line.size()){
		return;
	}
	char a;
	for(int i=left;i<line.size();i++){	
		for(int j=line.size()-1;j>left;j--){
			if(line[i]>line[j]){
				a = line[i];
				line[i] = line[j];
				line[j] = a;
			}
		}
	}
	left++;
	dfs(left);
}
main()
{
	int n,list;
	cin>>n;
	while(n--){
		cin>>list>>line;
		int leftN=-1,rightN=line.size();
		for(int i=0;i<rightN;i++){//从左往右
			for(int j=line.size()-1;j>i;j--){	//从右往左,到i过就行,要找的范围段一直在leftN后
				if(line[j]>line[i]&&i>leftN){
					leftN=i;	//找到最小的进行交换
					rightN=j;
				}
			}
		}
		if(leftN==-1){
			cout<<list<<" BIGGEST"<<endl;	//如果leftN没有改变那就说明没有交换的数字
		}else{
			char a;
			a = line[leftN];	
			line[leftN] = line[rightN];
			line[rightN] = a;	//交换
			dfs(leftN+1);	//递归
			cout<<list<<" "<<line<<endl;
		}
	}
}

我的代码可能有点难理解,上面的解释有点乱,挺菜的也不知道怎么讲,就将就看,有什么问题请大家指出。互啄一下。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

祖安大龙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值