1. 程式人生 > >ACM_下一個排列

ACM_下一個排列

cout urn possibly sets 解題思路 數據集 ret mut The

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。

Input:

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.
譯文:第一行輸入包含一個整數P,(1≤P≤1000),這是後面的數據集的數量。
每個數據集都是一行,其中包含數據集編號,後跟一個空格,然後是最多80個十進制數字,即輸入值。

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 }

ACM_下一個排列