您的位置:首页 > 其它

最短路径_求最小值(牵马从a到b,求最短时间)

2014-05-09 21:31 1141 查看
题目: n匹马从A村运往B村,每次骑1匹马牵1匹马,回来时骑1匹马。已知每匹马从A村到B村需要的时间(数字越大越慢)

两匹马同行时只能迁就较慢者。

求最小的运输时间。

输入:

4

1

4

2

5

程序应该输出:

12

思考:如何牵马才是最短时间呢?拿上述例子参考:4匹马耗时分别是1,4, 2,5



算法思路就是在保证每次返回是最小的情况下,将a中的所有马,任意两种组合;递归求出最小耗时的方案:

package cn.itcast.demo;
import java.util.*;

public class shortestPath
{
	static Map map = new HashMap();
	
	static String listToString(List a, List b)
	{
		Collections.sort(a);
		Collections.sort(b);
		
		return a.toString() + b.toString();
	}
	
	// a: A村马,b: B村马,人在A村
	public static int f(List a, List b)
	{
		Integer tt = (Integer)map.get(listToString(a,b));
		if(tt!=null) return tt;
		
		if(a.size()==2) return (Integer)a.get(1);
		
		int min = Integer.MAX_VALUE;
		
		for(int i=0; i<a.size()-1; i++){
			for(int j=i+1; j<a.size(); j++){				
				List la = new Vector(a);
				List lb = new Vector(b);
				
				//从a中取两匹马
				int x = (Integer)la.get(i);
				int y = (Integer)la.get(j);
				
				//b准备接受从a中牵过来的马,相应的a中少了两匹马,这里当然都是指时间
				lb.add(la.remove(j));
				lb.add(la.remove(i));
				
				Collections.sort(lb);
				//z记录下b中的一匹‘回头马’返回的时间
				int z = (Integer)lb.get(0);
				la.add(lb.remove(0));
				Collections.sort(la);
				
				//如此递归的计算运马的总时间
				int time = (x>y? x : y) + z + f(la,lb);
				if(time<min) min = time;
			}
		}
		
		map.put(listToString(a,b),min);
		return min;
	}
	
	public static void main(String[] args)
	{
		List a = new Vector();
		a.add(1);
		a.add(2);
		a.add(4);
		a.add(5);
		List b = new Vector();
		
		System.out.println(f(a,b));
	}
}
答案:12;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: