基础dfs,输出要求还真是多,可以用stl做,不过自己还是手写了一下。
1 #include <algorithm> 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5 6 const int N = 4; 7 const int M = 24; 8 const int K = 1000; 9 int index; 10 int num[N]; 11 bool visit[N]; 12 int tmp[N]; 13 int ans[M + 1]; 14 int cnt; 15 16 struct Node 17 { 18 int num[N]; 19 } node[K]; 20 21 void dfs( int i ) 22 { 23 if ( i == 4 ) 24 { 25 int sum = 0; 26 for ( int j = 0; j < 4; j++ ) 27 { 28 sum = sum * 10 + tmp[j]; 29 } 30 ans[cnt++] = sum; 31 return ; 32 } 33 for ( int k = 0; k < 4; k++ ) 34 { 35 if ( !visit[k] ) 36 { 37 visit[k] = 1; 38 tmp[i] = num[k]; 39 dfs( i + 1 ); 40 visit[k] = 0; 41 } 42 } 43 } 44 45 void solve( int p ) 46 { 47 for ( int i = 0; i < N; i++ ) 48 { 49 num[i] = node[p].num[i]; 50 } 51 cnt = 0; 52 memset( visit, 0, sizeof(visit) ); 53 dfs(0); 54 sort( ans, ans + cnt ); 55 for ( int i = 0; i < cnt - 1; i++ ) 56 { 57 if ( ans[i] == ans[i + 1] ) 58 { 59 for ( int j = i; j < cnt - 1; j++ ) 60 { 61 ans[j] = ans[j + 1]; 62 } 63 cnt--; 64 i--; 65 } 66 } 67 ans[cnt++] = 9999999; 68 int i = 0; 69 while ( ans[i] < 1000 ) i++; 70 int sp = ans[i] / 1000; 71 for ( ; i < cnt - 1; i++ ) 72 { 73 cout << ans[i]; 74 if ( ans[i + 1] / 1000 == sp ) 75 { 76 cout << ' '; 77 } 78 else 79 { 80 cout << endl; 81 sp = ans[i + 1] / 1000; 82 } 83 } 84 } 85 86 int main() 87 { 88 index = 0; 89 while ( 1 ) 90 { 91 int s = 0; 92 for ( int i = 0; i < 4; i++ ) 93 { 94 cin >> node[index].num[i]; 95 s += node[index].num[i]; 96 } 97 if ( !s ) break; 98 index++; 99 } 100 for ( int i = 0; i < index; i++ ) 101 { 102 solve(i); 103 if ( i != index - 1 ) cout << endl; 104 } 105 return 0; 106 }