最短路径_求最小值(牵马从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中的所有马,任意两种组合;递归求出最小耗时的方案:
两匹马同行时只能迁就较慢者。
求最小的运输时间。
输入:
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;
相关文章推荐
- 揽货最短路径解决方案算法 - V2(增加了时间维度-客户允许的服务时间段,C#/JAVA同步实现,带python作图)
- POJ3268 牛的最长来回时间(单源最短路径)
- 每对顶点间的最短路径算法时间复杂度改进C++实现
- 课程设计 最小时间 最短路径 模板 .
- 数据结构-关键路径 (最短时间)
- 课程设计 最小时间 最短路径 模板 .
- 课程设计 最小时间 最短路径 模板 .
- LA 2957 最大流,最短时间,输出路径
- 课程设计 最小时间 最短路径 模板 .
- 每对顶点间最短路径;Floyd算法;写的很乱,判断太多了;没有用动态规划过程中构建路径;用O(n三次方)时间构造路径;
- 坦克大战(最短时间和最短路径输出)
- 时间复杂度最小的最短路径算法?由这个想到的
- HDU 3790 最短路径问题(Dijkstra,要求距离和时间都最短)
- 每对顶点间的最短路径算法时间复杂度改进C++实现
- 最短路径问题总结,时间复杂度,空间复杂度对比(JAVA)
- 课程设计 最小时间 最短路径 模板 .
- 课程设计 最小时间 最短路径 模板 .
- 课程设计 最小时间 最短路径 模板 .
- 【WA】题目1100:最短路径
- hdoj 3790 最短路径问题