頭文件:#include<algorithm>
* * *
1. next_permutation():
next_permutation()函數的返回類型是bool類型.
即:如果有一個更高的排列,它重新排列元素,並返回true;如果這是不可能的(因為它已經在最大可能的排列),它按升序排列重新元素,並返回false。
使用:
next_permutation,重新排列范圍內的元素[第一,最后一個)返回按照字典序排列的下一個值較大的組合。
next_permutation()函數功能是輸出所有比當前排列大的排列,順序是從小到大。
算法描述:
從尾部開始往前尋找兩個相鄰的元素
第1個元素i,第2個元素j(從前往后數的),且i<j
2、再從尾往前找第一個大於i的元素k。將i、k對調
3、[j,last)范圍的元素置逆(顛倒排列)
2. prev_permutation():
prev_permutation()函數功能是輸出所有比當前排列小的排列,順序是從大到小。
例:
K—排列2
Ray又對數字的列產生了興趣:
現有四張卡片,用這四張卡片能排列出很多不同的4位數,要求按從小到大的順序輸出這些4位數。
Input每組數據占一行,代表四張卡片上的數字(0<=數字<=9),如果四張卡片都是0,則輸入結束。
Output對每組卡片按從小到大的順序輸出所有能由這四張卡片組成的4位數,千位數字相同的在同一行,同一行中每個四位數間用空格分隔。
每組輸出數據間空一行,最后一組數據后面沒有空行。
Sample Input
1 2 3 4 1 1 2 3 0 1 2 3 0 0 0 0
Sample Output
1234 1243 1324 1342 1423 1432
2134 2143 2314 2341 2413 2431
3124 3142 3214 3241 3412 3421
4123 4132 4213 4231 4312 4321
1123 1132 1213 1231 1312 1321
2113 2131 2311
3112 3121 3211
1023 1032 1203 1230 1302 1320
2013 2031 2103 2130 2301 2310
3012 3021 3102 3120 3201 3210
代碼:
#include<iostream> #include<algorithm> //next_permutation
using namespace std; int deal(int n) { int sum=1; for (int i=1;i<=n;i++) sum*=i; return sum; } int main() { int x[5],f,flag=0; while (1) { cin>>x[0]>>x[1]>>x[2]>>x[3]; if(x[0]==0&&x[1]==0&&x[2]==0&&x[3]==0) return 0; if(flag!=0) cout << endl; flag=1; int w=0; sort(x,x+4); //排序,默認升序,頭文件algorithm
f=0; do { if (x[0]==0) continue; if (f==0) { cout << x[0] << x[1] << x[2] << x[3] ; f=1; } else { if (w==x[0]) cout << ' ' << x[0] << x[1] << x[2] << x[3] ; else cout << endl << x[0] << x[1] << x[2] << x[3] ; } w=x[0]; } while (next_permutation(x,x+4)); cout << endl; } return 0; }
注意輸出格式:是輸入一組數據后換行輸出結果