过桥问题

【题目描述】

 

 

 

今天无意中看见一道微软面试题,很有意思,大家一起来看一下:
 

四人夜过桥,步行时间分别为 1、2、5、10 分钟,四人只有一台手电筒,一趟最多两人过桥,一趟过桥须持手电筒,时间以最慢者计,问 17 分钟内可否过桥,如何过桥?

 

 

 

 

 

【本题答案】

 

 

 

这个是一位其他的博主做的答案,我先分享给大家:

#define STATE char  
#define PATH char  
const int TimeLimit = 17;  
STATE State[16] = { 1 };  
PATH Path[16];  
const int Cop[10] = { 1, 2, 4, 8, 3, 5, 9, 6, 10, 12 };  
const char* Cops[10] =  
{  
    "1,耗时 1 分",  
    "2,耗时 2 分",  
    "5,耗时 5 分",  
    "10,耗时 10 分",  
    "1 和 2,耗时 2 分",  
    "1 和 5,耗时 5 分",  
    "1 和 10,耗时 10 分",  
    "2 和 5,耗时 5 分",  
    "2 和 10,耗时 10 分",  
    "5 和 10,耗时 10 分"  
};  
const int Time[10] = { 1, 2, 5, 10, 2, 5, 10, 5, 10, 10 };  
void Ferry ( int state, int dir, int p, int time )  
{  
    int i, cop, j;  
    for ( i = 0; i < 10; i++ )  
    {  
        if ( Cop[i] != (cop = state & Cop[i] ) ) continue;  
        state &= ~cop;  
        time += Time[i];  
        if ( State[ dir ? ~state & 15 : state ] ||  
            time > TimeLimit )  
        {  
            state |= cop;  
            time -= Time[i];  
        }  
        else if ( dir && !state )  
        {  
            Path[p] = i;  
            printf ( "过桥过程,共往返 %d 次:/n", p + 1 );  
            for ( j = 0; j <= p; j++ )  
                printf ( "%s: %s/n", ( j & 1 ? "右往左" : "左往右" ), Cops[Path[j]] );  
            printf ( "/n" );  
            break;  
        }  
        else  
        {  
            State[ dir ? ~state & 15 : state ] = 1;  
            Path[p] = i;  
            Ferry ( ~state & 15, !dir, p + 1, time );  
            State[ dir ? ~state & 15 : state ] = 0;  
            time -= Time[i];  
            state |= cop;  
        }  
    }  
}  
// 调用时  
Ferry ( 15, 1, 0, 0 );  

 

 

今天无意中想起递归算法,突生灵感,如果用Java语言实现“n人过桥”问题,那就有意思了。

递归的出口是:“2人过桥”情况。2人过桥,不需要有人返回,所以非常简单,总时间就是单人所需时间中的最大值。

如果是“n人过桥”(n>=3),那完全可以递归了。

假设是从桥头A至桥头B,桥头A的人群为一个集合,桥头B的人群为另一个集合。

那么首先可以从A中任意选择2个人从A到B;则A集合中减少2个人,B集合中增加2个人;

然后需要一个人从B返回A,这个可以分析出如果想要比较少的时间,一定是从B中选一个单独需时最短的;此时B中减少一个人,A集合中增加一个人;

之后情况变成了“n-1人过桥”问题。

递归思想就开始起作用了。

 

但是需要注意一点,我在这里的思想是每次返回的人都是从B集合中选出需时最少的;如果想找出需时最多的,就从B中选出一个需时最大的;如果想找到所有情况,那就需要遍历B集合,那就比较复杂了,我没有考虑。

 

如下是我的代码,由于时间仓促,没有规范化处理。。。比如passMethod中的参数列表中第三个参数其实是可以去掉的,因为它就是桥头A端得人数,可以从第一个参数中获得。

由于时间有限,我在这里就不改动了。

 

读者可以自己个界面,允许人/机交互,如果深入思考,还是很有意思的。

 

 

package blog;

import java.util.Vector;

/**
 * @author yesr
 * @create 2018-04-22 上午12:05
 * @desc
 **/
 public class BridgePass {

    private Vector v_source = null;
    private Vector v_destination = null;
    private static int time_total = 0;

    public BridgePass() {
        v_source = new Vector();
        v_destination = new Vector();
    }

    public void setSource(int[] array, int num) {
        for (int i = 0; i < num; i++) {
            v_source.addElement(array[i]);
        }
    }

    public Vector getSource() {
        return v_source;
    }

    public Vector getDestination() {
        return v_destination;
    }

    /**
     * the recursive algorithm.
     *
     * @param src       : the set of persons in A-side
     * @param des       : the set of persons in B-side
     * @param size      : the number of persons in A-side
     * @param totalTime : the totalTime has used
     */
    public void passMethod(Vector src, Vector des, int size, int totalTime) {

        //If only 2 persons in A-side, just pass bridge together in one time.
        if (size == 2) {
            System.out.println("A->B:" + src.elementAt(0) + " AND " + src.elementAt(1));
            System.out.println("*****Total Time: " + (totalTime + Math.max((Integer) src.elementAt(0), (Integer) src.elementAt(1))) + "****");
        } else if (size >= 3) {

            // if more than 2 persons in A-Side, use the recursive algorithm.
            for (int i = 0; i < size; i++) {
                for (int j = i + 1; j < size; j++) {
                    System.out.println("i=" + i + "j=" + j);
                    //Pass, A->B

                    Vector _src = new Vector();
                    Vector _des = new Vector();
                    _src = (Vector) src.clone();
                    _des = (Vector) des.clone();

                    int time1 = 0;
                    int time2 = 0;

                    time1 = (Integer) _src.elementAt(i);
                    _des.addElement(time1);

                    time2 = (Integer) _src.elementAt(j);
                    _des.addElement(time2);

                    System.out.print("A->B:" + time1);
                    System.out.println(" AND " + time2);

                    _src.removeElement(time1);
                    _src.removeElement(time2);

                    //BACK, B->A

                    int minValue = (Integer) _des.elementAt(0);
                    for (int k = 0; k < _des.size(); k++) {
                        if (((Integer) _des.elementAt(k)).intValue() < minValue) {
                            minValue = (Integer) _des.elementAt(k);
                        }
                    }

                    _src.addElement(minValue);
                    _des.removeElement(minValue);

                    System.out.println("B->A:" + minValue);

                    passMethod(_src, _des, _src.size(), totalTime + Math.max(time1, time2) + minValue);

                }

            }
        }
    }


    public static void main(String[] cmd) {
        BridgePass test = new BridgePass();

        //the persons want to pass bridge:
        int source[] = {1, 2, 5, 10};

        test.setSource(source, source.length);
        test.passMethod(test.getSource(), test.getDestination(), source.length, 0);


    }
}

 

 

 

 

 

六人过桥问题是一个经典的优化问题,目标是让所有人在最短的时间内全部过桥。这个问题通常需要使用贪心算法或动态规划来解决,但通过合理的策略可以找到最优解。 ### 问题描述 - 有六位旅行者:A、B、C、D、E 和 F。 - 每个人单独过桥所需的时间分别是 1、5、6、7、8 和 9 分钟。 - 只有一只手电筒,且桥只能同时容纳两个人。 - 当两人一起过桥时,过桥时间等于较慢的那个人的时间。 ### 解决方案 该问题的一个常见解决方案是基于“快速来回”原则设计的策略,即让速度较快的人负责多次往返送手电筒,从而减少整体时间消耗。以下是具体的步骤: 1. **首先安排两个最快的人过桥**: - 让 A(1分钟)和 B(5分钟)先过桥,耗时 5 分钟。 2. **让最快的人返回**: - 让 A 返回,耗时 1 分钟。 3. **安排两个最慢的人过桥**: - 让 C(6分钟)、D(7分钟)过桥,耗时 7 分钟。 4. **让另一个快的人返回**: - 让 B 返回,耗时 5 分钟。 5. **再次让两个最快的人过桥**: - 让 A 和 B 过桥,耗时 5 分钟。 6. **重复类似策略处理剩下的两个人**: - 让 E(8分钟)和 F(9分钟)过桥,耗时 9 分钟。 - 让 A 返回,耗时 1 分钟。 - 最后,让 A 和 B 过桥,耗时 5 分钟。 将上述时间相加: - 第一轮:5 + 1 = 6 分钟 - 第二轮:7 + 5 = 12 分钟 - 第三轮:5 + 1 = 6 分钟 - 第四轮:9 + 5 = 14 分钟 总时间为:6 + 12 + 6 + 14 = **38 分钟** ### 算法实现 下面是一个简单的 Python 实现示例,用于计算最优过桥时间: ```python def bridge_crossing_times(people): people.sort() # 按照过桥时间排序 total_time = 0 n = len(people) while n > 3: # 使用两种策略中的较小值 strategy1 = people[0] + people[1] + people[1] + people[-1] strategy2 = people[0] + people[-2] + people[-1] + people[0] total_time += min(strategy1, strategy2) people.pop() people.pop() n -= 2 if n == 3: total_time += sum(people) # A 带其他人过桥 elif n == 2: total_time += people[-1] else: total_time += people[0] return total_time # 六人的过桥时间 times = [1, 5, 6, 7, 8, 9] optimal_time = bridge_crossing_times(times.copy()) print(f"最优过桥时间为: {optimal_time} 分钟") ``` ### 结论 该问题的关键在于如何利用最快的两个人(如 A 和 B)来最小化手电筒的传递时间,并在适当的时候让最慢的两个人一起过桥以减少额外的时间消耗。最终的最优时间是 **38 分钟**,这是在合理策略下所能达到的最佳结果[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值