題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1716
The title
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
思路:
全排列,注意題目要求的格式,我一度認為這是一道格式題,在解法上我們可以選擇回圈嵌套模擬或者使用庫內自帶函式 ”next_permutation()“,這個函式的詳細用法可見 C++ Primer第778頁 ,
雖然我是使用函式寫的,但我僅是第一次使用這個函式做一個嘗試,并不推薦,因為這題的格式要求很多,所以建議直接回圈嵌套模擬,在模擬的程序中就可以對格式做出調整,輕松很多,
Code:
#include <bits/stdc++.h>
#include <algorithm>
#define PI 3.141593
#define INF 0x3f3f3f3f
#define Best 0x7fffffff
using namespace std;
int a[700000];
int main() {
ios::sync_with_stdio(false);
//int n;
int n, p = 0, s, k = 0;
while (cin >>a[0]>>a[1]>>a[2]>>a[3], a[0], a[1], a[2],a[3]) {
/*for (int i = 0; i < 4; i++) {
cin >> a[i];
}*/
//p = 0;
/*if (a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0) {
break;
}*/
sort(a, a + 4);
/*if (a[0] != 0) {
cout << a[0] << a[1] << a[2] << a[3] << " ";
}*/
if (p != 0) {
cout << endl;
}
p++;
int x = 0;
int m = a[0], s = 1;
if (a[k] == 0) {
m = a[k++];
}
do {
/*for (int i = 0; i < 4; ++i)
cout << a[i];
cout << " ";*/
if (a[0] == 0) {
continue;
}
//else {
/*for (int i = 0; i < 4; ++i)
cout << a[i];
cout << " ";*/
//}
if (s) {
cout << a[0] << a[1] << a[2] << a[3] ;
s = !s;
}
else if (a[0] == m) {
cout << " " << a[0] << a[1] << a[2] << a[3];
}
else {
cout << endl;
cout << a[0] << a[1] << a[2] << a[3];
//cout << endl;
}
m = a[0];
//s = a[0];
/*if (s == a[0])
cout << a[0] << a[1] << a[2] << a[3];
else {
cout << endl;
cout << a[0] << a[1] << a[2] << a[3];
}
s = a[0];*/
//cout << endl;
} while (next_permutation(a, a + 4));
cout << endl;
}
//猝不及防的周末訓練打亂了我的計劃也打亂了我的心,同時也幫我打開了C++ Primer第778頁 :)代碼十分鐘格式一小時
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/143961.html
標籤:其他
