中级农民
- 积分
- 232
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2010-6-11
- 最后登录
- 1970-1-1
|
个人感觉DP做不了那个飞机票的题目。面试官是不是期待dp做记录中间结果呢?不知道。。。掐表写了个graph DFS的,找到所有路径-》计算cost-》找到最小 写完了已经43分钟了。。。
- import java.util.*;
- public class flightMinCost {
-
- public int minCost(String[] input, char source, char dest, int k){
- HashMap<Character, HashMap<Character, Integer>> graph = new HashMap<>();
-
- //build a graph
- for(String s : input){
- String [] arr = s.split(",");
- char start = arr[0].charAt(0);
- char end = arr[0].charAt(3);
- int cost = Integer.parseInt(arr[1]);
-
- if(!graph.containsKey(start)){
- HashMap<Character, Integer> map = new HashMap<Character, Integer>();
- map.put(end, cost);
- graph.put(start, map);
- }
- else{
-
- HashMap<Character, Integer> m = graph.get(start);
- m.put(end, cost);
- }
- }
- List<Character> path = new ArrayList<>();
- List<List<Character>> allPath = new ArrayList<>();
- HashSet<Character> visited = new HashSet<>();
-
- helper(source, dest, path, allPath, graph, visited);
-
- for(char c : graph.keySet()){
- HashMap<Character, Integer> m = graph.get(c);
- for(Character nei : m.keySet()){
- System.out.println("source is: " + c +" dest is:" + nei + " cost is: " + m.get(nei));
- }
- }
-
- int minCost = Integer.MAX_VALUE;
-
- for(List<Character> p : allPath){
- if(p.size() < k){
- int cost = getCost(graph, p);
- minCost = Math.min(cost, minCost);
- }
- }
-
- return minCost;
- }
-
- int getCost(HashMap<Character, HashMap<Character, Integer>> graph, List<Character> p){
- int sum = 0;
-
- for(int i=0; i<p.size()-1; i++){
- char start = p.get(i);
- char dest = p.get(i+1);
- sum += graph.get(start).get(dest);
- }
- return sum;
- }
-
- void helper(Character source, Character dest,List<Character> path,List<List<Character>> allPath,
- HashMap<Character, HashMap<Character, Integer>> graph, HashSet<Character> visited ){
-
- visited.add(source);
- path.add(source);
-
- if(source == dest){
- allPath.add(new ArrayList<>(path));
- }
- else{
- Set<Character> neis = graph.get(source).keySet();
-
- for(char n : neis){
- if(!visited.contains(n)){
- helper(n, dest, path, allPath, graph, visited);
- }
- }
- }
-
- path.remove(path.size()-1);
- visited.remove(source);
- }
-
-
-
- public static void main(String[] args) {
- flightMinCost fmc = new flightMinCost();
- String [] input = {
- "A->B,8",
- "B->C,4",
- "A->D,1",
- "D->E,2",
- "E->B,3"
- };
-
- System.out.println(fmc.minCost(input, 'A', 'C', 12));
-
- }
- }
复制代码 |
|