习题2-6 排列(permultation)

  • Post author:
  • Post category:其他




习题2-6 排列(permultation)

题目描述:用1,2,3…,9 组成3个三位数 abc,def 和 ghi,每个数字恰好使用一次,要求 abc:def:ghi=1:2:3。按照“abc def ghi”的格式输出所有解,每行一个解。提示:不必太动脑筋。

总结:用的是最笨的办法,不过也体现了暴力枚举的特点。

看了一下别人的方法,即使是用暴力枚举,也都会先界定范围,

比如abc既然是三位数,且是ghi的三分之一,ghi最大为987,

那么abc的范围就可以界定为123到329,然后乘以2和3,就得到def和ghi了,再判断是否符合条件,符合就输出。这样减少了不少运行时间和空间。

多看看别人的思路和代码,千万不能闭门造车。

#include <stdio.h>

int main()
{
    int a,b,c,d,e,f,g,h,i;

    for (a = 1; a <= 9; a++ ) {
        for (b = 1; b <= 9; b++ ) {
            if( b == a ) continue;
            for (c = 1; c <= 9; c++ ) {
                if( c == b || c == a) continue;
                for (d = 1; d <= 9; d++ ) {
                    if (d == a || d == b || d == c) continue;
                    for (e = 1; e <= 9; e++ ) {
                        if ( e == a || e == b || e == c || e == d ) continue;
                        for (f = 1; f <= 9; f++ ) {
                            if ( f == a || f == b || f == c || f == d || f == e ) continue;
                            for (g = 1; g <= 9; g++ ) {
                                if ( g == a || g == b || g == c || g == d || g == f || g ==e ) continue;
                                for (h = 1; h <= 9; h++ ) {
                                    if ( h == a || h == b || h ==c || h == d || h == e || h == f || h == g ) continue;
                                    for (i = 1; i <= 9; i++ ) {
                                        if( i == a || i == b || i == c || i == d || i == e || i == f || i == g || i ==h ) continue;
                                        if ((a*100 + b*10 + c)*3 == (g*100 + h*10 + i) && (a*100 + b*10 + c)*2 == (d*100 + e*10 + f)) printf("%d %d %d\n",a*100 + b*10 + c,d*100 + e*10 + f,g*100 + h*10 + i);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return 0;
}



版权声明:本文为weixin_43728235原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。