zoukankan      html  css  js  c++  java
  • 算法竞赛入门经典ch2_practice6排列abc def ghi 1 2 3

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

    我没有想出来。

    要点:
    - 枚举

    这个枚举要技巧,并不是9个for循环,看1:2:3这个规律,abc最小为123,最大的是ghi,它不能超过999,所abc最大是333,但是不能有相同的数字,所以abc最大为329。这样循环的次数就确定了,即abc从123-329,比9个for循环高效。
    
    • 判断是否有重复

      用一个包含10个元素的数组,初始化为1来做标记,依次用取余的方式判断,看代码更好理解。

    code

    #include "stdio.h"
    int isRepeat(int n)//没有重复返回1
    {
        //flag用的非常巧妙,注意1的用途,用来排除数字0
        int lastNumber, flag[10] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
        for (lastNumber = n%10; n; n /= 10, lastNumber = n % 10)
        {
            if (flag[lastNumber]++ == 1)
            {
                return 0;
            }
        }
        return 1;
    }
    
    int main()
    {
    
        for (int base = 123; base <= 329; base++)
        {
            if (isRepeat(base * 1000000 + base * 2 * 1000 + base * 3) == 1)
            {
                printf("%d %d %d
    ", base, base * 2, base * 3);
            }
        }
        return 0;
    }

    注解

    • 排除0

      虽然abc是从123到329,但这中间有0的出现,即使符合1:2:3的条件也要去除比如 267 534 801。解决办法是巧用flag,它的位数为10位不是无缘无故的!初始化的时候直接将flag[0]设为1,这样如果有0出现就会返回0;

  • 相关阅读:
    Sicily shortest path in unweighted graph
    Sicily connect components in undirected graph
    Sicily 1931. 卡片游戏
    Sicily 1021. Couples
    c++ 高效文本读写
    Sicily 1129. ISBN
    Sicily 1133. SPAM
    Sicily 1282. Computer Game
    小工具?不,这是小工具的集合!
    .Net Core建站(4):FTP发布项目及连接服务器数据库
  • 原文地址:https://www.cnblogs.com/shanchuan/p/8150304.html
Copyright © 2011-2022 走看看