zoukankan      html  css  js  c++  java
  • 《Cracking the Coding Interview》——第6章:智力题——题目3

    2014-03-20 00:48

    题目:有3升的瓶子和5升的瓶子,只允许倒满、倒到满为止、或是泼光三种操作,怎么搞出4升水呢?

    解法:如果A和B是互质的两个正整数,且A<B,令X=B-A,则(X%B, 2X%B, 3X%B, ..., BX%B)正好就是0~n-1的一个排列。也就是说,两瓶子的容积如果互质,就可以配出0~B之间的任意容积。至于怎么配,请看代码。

    代码:

     1 // 6.3 Given two jugs with size x and y, and a volume v between 0 and y inclusive. Show how you're gonna get that value.
     2 // Note that you can only fill a jug, empty a jug or pour from one into another.
     3 // x and y will be positive and relatively prime.
     4 #include <cstdio>
     5 using namespace std;
     6 
     7 int gcd(int x, int y)
     8 {
     9     return x == 0 ? y : gcd(y % x, x);
    10 }
    11 
    12 int main()
    13 {
    14     int x, y;
    15     int vx, vy;
    16     int v;
    17     
    18     while (scanf("%d%d%d", &x, &y, &v) == 3 && (x > 0 && y > 0 && v > 0)) {
    19         if (x > y) {
    20             continue;
    21         }
    22         if (gcd(x, y) > 1) {
    23             continue;
    24         }
    25         
    26         vx = 0;
    27         vy = y;
    28         printf("[%d, %d]: fill y
    ", vx, vy);
    29         while (vy != v) {
    30             if (vy < x) {
    31                 vx = vy;
    32                 vy = 0;
    33                 printf("[%d, %d]: pour y into x
    ", vx, vy);
    34                 vy = y;
    35                 printf("[%d, %d]: fill y
    ", vx, vy);
    36                 vy = vy - (x - vx);
    37                 vx = x;
    38                 printf("[%d, %d]: pour y into x
    ", vx, vy);
    39                 vx = 0;
    40                 printf("[%d, %d]: empty x
    ", vx, vy);
    41             } else {
    42                 vy -= x;
    43                 vx = x;
    44                 printf("[%d, %d]: pour y into x
    ", vx, vy);
    45                 vx = 0;
    46                 printf("[%d, %d]: empty x
    ", vx, vy);
    47             }
    48         }
    49     }
    50     
    51     return 0;
    52 }
  • 相关阅读:
    linux启动init流程(转)
    .bash_profile .bashrc profile 文件的作用的执行顺序(转)
    Linux常用命令
    面试中常见的问题
    systemd启动过程(转)
    .bashrc文件是干什么的(转)
    关于 profile文件(转)
    从MVC框架看MVC架构的设计(转)
    Java高级软件工程师面试考纲(转)
    关于Python中的lambda
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3612733.html
Copyright © 2011-2022 走看看