[OI - STL] next_permutation( ) & prev_permutation( )函數
阿新 • • 發佈:2018-10-25
prev ret true debug code return cout 函數 需要
next_permutation( ) 和 prev_permutation( ) 函數基本類似,都需要用到頭文件名<algorithm>
next_permutation()函數
用法:next_permutation(first,last)
作用:next_permutation()函數將 [ first , last ] 區間中的序列轉換為字典序的下一個排列。如果下一個排列存在返回true,如果下一個排列不存在(即區間中包含的是字典序的最後一個排列),則該函數返回false,並將區間轉換為字典序的第一個排列。
代碼實現
1 #include <iostream> 2#include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 6 using namespace std; 7 //#define DEBUG(x) cerr << #x << "=" << x << endl 8 const int maxn = 1e5 + 10; 9 10 int n, f[maxn]; 11 int main() 12 { 13 //ios::sync_with_stdio(false); 14 cin.tie(0); 15 cin >> n; 16 for (int i = 0; i < n; i++) cin >> f[i]; 17 sort(f, f + n); 18 do 19 { 20 for (int i = 0; i < n; i++) cout << f[i] << " "; 21 //cout << endl; 22 puts(""); 23 }while (next_permutation(f, f + n)); 24 return0; 25 }
prev_permutation()函數
用法:prev_permutation(first,last)
作用:prev_permutation()函數將 [ first , last ] 區間中的序列轉換為字典序的上一個排列。如果上一個排列存在返回true,如果上一個排列不存在(即區間中包含的是字典序的第一個排列),則該函數返回false,並將區間轉換為字典序的最後一個排列。
代碼實現
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 6 using namespace std; 7 //#define DEBUG(x) cerr << #x << "=" << x << endl 8 const int maxn = 1e5 + 10; 9 10 int n, f[maxn]; 11 12 int cmp(int a, int b) 13 { 14 return a > b; 15 } 16 17 int main() 18 { 19 //ios::sync_with_stdio(false); 20 cin.tie(0); 21 cin >> n; 22 for (int i = 0; i < n; i++) cin >> f[i]; 23 sort(f, f + n, cmp); 24 do 25 { 26 for (int i = 0; i < n; i++) cout << f[i] << " "; 27 //cout << endl; 28 puts(""); 29 }while (prev_permutation(f, f + n)); 30 return 0; 31 }
[OI - STL] next_permutation( ) & prev_permutation( )函數