The Next Permutation
Time Limit: 2000/1000ms (Java/Others)
Problem Description:
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.
译文:对于这个问题,你将编写一个程序,它接受一个(可能很长的)十进制数字串,并输出具有比输入数字更大的值(十进制数)的那些十进制数字的排列。例如:
123 - > 132
279134399742 - > 279134423799
输入数字的排列可能没有更大的值。例如,987。
Output:
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.
译文:对于每个数据集有一行输出。如果输入数字没有大的排列,则输出应该是数据集编号,后跟一个空格,然后是字符串BIGGEST。如果有解决方案,输出应该是数据集编号,一个空格和下一个较大的输入数字排列。
Sample Input:
3
1 123
2 279134399742
3 987
Sample Output:
1 132
2 279134423799
3 BIGGEST
解题思路:80个10进制数字,即80位数,基本数据类型都不能表示,但C++万能的STL中有next_permutation,用它即可解决此题是否有下一个排列。
str.begin()和str.end() 可以快速访问到字符串的首字符和尾字符。如果有下一个排列,next_permutation(str.begin(), str.end())为真值,否则为假值。
AC代码:
1 #include<bits/stdc++.h>
2 using namespace std;
3 int main()
4 {
5 int p,n;string str;
6 cin>>p;
7 for(int i=1;i<=p;++i){
8 cin>>n>>str;
9 cout<<n<<' ';
10 if(next_permutation(str.begin(),str.end()))cout<<str<<endl;
11 else cout<<"BIGGEST"<<endl;
12 }
13 return 0;
14 }