【题目描述】
用1, 2,3,...,9组成3个三位数abc,def和ghi,每个数字恰好使用一次,要求 abc : def : ghi = 1 : 2 : 3。
按照“abc def ghi”的格式输出所有解,每行一个解。提示:不必太动脑筋。
【代码实现】
方法1
1 #include <iostream> 2 #include <cstdio> 3 4 using namespace std; 5 6 int main() 7 { 8 for ( int a = 1; a < 10; a++ ) { 9 for ( int b = 1; b < 10; b++ ) { 10 if ( b == a ) continue; 11 for ( int c = 1; c < 10; c++ ) { 12 if ( c == a || c == b) continue; 13 for ( int d = 1; d < 10; d++ ) { 14 if ( d == a || d == b || d == c ) continue; 15 for ( int e = 1; e < 10; e++ ) { 16 if ( e == a || e == b || e == c || e == d) continue; 17 for ( int f = 1; f < 10; f++ ) { 18 if ( f == a || f == b || f == c || f == d || f == e ) continue; 19 for ( int g = 1; g < 10; g++ ) { 20 if ( g == a || g == b || g == c || g == d || g == e || g == f ) continue; 21 for ( int h = 1; h < 10; h++ ) { 22 if ( h == a || h == b || h == c || h == d || h == e || h == f || h == g ) continue; 23 for ( int i = 1; i < 10; i++ ) { 24 if ( i == a || i == b || i == c || i == d || i == e || i == f || i == g || i == h ) continue; 25 int abc = a*100 + b*10 + c; 26 int def = d*100 + e*10 + f; 27 int ghi = g*100 + h*10 + i; 28 if ( 2*abc == def && 3*abc == ghi ) { 29 printf ("%d %d %d\n", abc, def, ghi); 30 } 31 } 32 } 33 } 34 } 35 } 36 } 37 } 38 } 39 } 40 41 return 0; 42 }
方法2
1 #include <iostream> 2 #include <cstdio> 3 4 using namespace std; 5 6 int main() 7 { 8 for ( int l = 100; l < 1000/3; l++) { 9 int m = 2 * l; 10 int n = 3 * l; 11 12 int a = l / 100; 13 int b = (l - a*100) / 10; 14 int c = l % 10; 15 16 int d = m / 100; 17 int e = (m - d*100) / 10; 18 int f = m % 10; 19 20 int g = n / 100; 21 int h = (n - g*100) / 10; 22 int i = n % 10; 23 if ( a != b && a != c && a != d && a != e && a != f && a != g && a != h && a != i && a != 0 ) 24 if ( b != c && b != d && b != e && b != f && b != g && b != h && b != i && b != 0 ) 25 if ( c != d && c != e && c != f && c != g && c != h && c != i && c != 0 ) 26 if ( d != e && d != f && d != g && d != h && d != i && d != 0 ) 27 if ( e != f && e != g && e != h && e != i && e != 0 ) 28 if ( f != g && f != h && f != i && f != 0 ) 29 if ( g != h && g != i && g != 0 ) 30 if( h != i && h != 0 ) 31 printf ("%d %d %d\n", l, m, n); 32 } 33 34 return 0; 35 }
【总结】
这道题后面的提示吓到我了。。大概这句话是对大佬说的。。OTL,就现在能力来说除了暴力完全想不到其他方法,实际上这两个方法也都是暴力枚举。第一个是自己的思路,但具体实现的时候搞错了三个数的关系,a:b:c = 1:2:3 居然已经不会求了OTL 第二个方法是从别人的博客看的,对于每个数的拆分比较有意思,但是后来检查时发现了一个问题。。因为是从100 - 999的全部三位数拆分,一定会出现0,若不对0进行处理的话则最后的输出结果会有多出一行包含801的答案,而这个答案不符合题目要求。其实解决办法很简单。。对abcdefghi都进行非零判断就好了(笑