hdu 1716(dfs),hdu1716dfs
題目鏈接 : http://acm.hdu.edu.cn/showproblem.php?pid=1716
排列2
Problem Description
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
一道全排列的搜索題,思路是先把四個數字從小到大排列,然後把所有可能的四位數全找出來,最後輸出的時候把不符合題意的捨去就ok了。

![]()
1 #include <cstdio>
2 #include <cmath>
3 #include <cstring>
4 #include <algorithm>
5 using namespace std;
6
7 int a[4],vis[4],s[25];
8 int t,c;
9
10 void dfs(int num)
11 {
12 if (num == 4)
13 {
14 if (c>=1000)
15 s[t++] = c;
16 return ;
17 }
18 for (int i=0; i<4; i++)
19 {
20 if (!vis[i]) //標記訪問
21 {
22 vis[i] = 1;
23 c = c * 10 + a[i];
24 dfs(num + 1);
25 vis[i] = 0;
26 c = (c - a[i]) / 10;
27 }
28 }
29 }
30
31 int main ()
32 {
33 int flag = 0;
34 while (scanf ("%d%d%d%d",&a[0],&a[1],&a[2],&a[3]))
35 {
36 sort(a, a+4);
37 if (a[3] == 0)
38 break;
39 if (flag)
40 {
41 printf ("\n");
42 }
43 flag = 1;
44 memset(vis, 0, sizeof(vis));
45 t = c = 0;
46 dfs(0);
47 sort(s, s+t);
48 int temp;
49 printf ("%d",s[0]);
50 temp = s[0] / 1000; //記住千位數
51 for (int i=1; i<t; i++)
52 {
53 if (s[i] == s[i-1]) //因為排序過了,所以相同的四位數都在一起
54 continue ;
55 if (s[i] / 1000 != temp) //千位數不同,換行
56 {
57 printf ("\n%d",s[i]);
58 temp = s[i] / 1000; //同時記錄新的千位數
59 }
60 else
61 {
62 printf (" %d",s[i]);
63 }
64 }
65 printf ("\n");
66 }
67 return 0;
68 }
View Code
今天意外看到一位大神博客,用了一個next_permutation(a.begin(), a.end())函數,輕輕松松實現全排列。
附上大神博客鏈接和他的代碼 : http://www.cnblogs.com/jackge/archive/2013/05/22/3093089.html

![]()
1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<algorithm>
5
6 using namespace std;
7
8 int main(){
9
10 //freopen("input.txt","r",stdin);
11
12 int a[5],tag=0;
13 while(scanf("%d%d%d%d",&a[0],&a[1],&a[2],&a[3])){
14 if(a[0]==0 && a[1]==0 && a[2]==0 && a[3]==0)
15 break;
16 if(tag)
17 printf("\n");
18 tag=1;
19 int flag=1,tmp;
20 do{
21 if(a[0]==0)
22 continue;
23 if(flag){
24 printf("%d%d%d%d",a[0],a[1],a[2],a[3]);
25 flag=0;
26 }else if(tmp==a[0])
27 printf(" %d%d%d%d",a[0],a[1],a[2],a[3]);
28 else
29 printf("\n%d%d%d%d",a[0],a[1],a[2],a[3]);
30 tmp=a[0];
31 }while(next_permutation(a,a+4));
32 printf("\n");
33 }
34 return 0;
35 }
View Code