树上最大得分

题目

代码

代码中包含两种方式:getMaxScore2()只能过82%,会超时,getMaxScore()会使用额外的空间

import java.util.*;
public class Solution {
    /**
     * @param x: The vertex of edge
     * @param y: The another vertex of edge
     * @param cost: The cost of edge
     * @param profit: The profit of vertex
     * @return: Return the max score
     */
    public int getMaxScore2(int[] x, int[] y, int[] cost, int[] profit) {
        // Write your code here
        return getMaxScoreCore2(x,y,cost,profit,0);
    }
    public int getMaxScoreCore2(int[] x, int[] y, int[] cost, int[] profit,int start){
        int sum=Integer.MIN_VALUE;
        boolean flag=false;
        for (int i=0;i<x.length;i++){
            if(x[i]==start){
                int next=getMaxScoreCore2(x,y,cost,profit,y[i]);
                int temp=profit[start]-cost[i]+next;
                sum=sum>=temp?sum:temp;
                //System.out.printf("profit[i]:%d,cost[i]:%d,temp:%d,sum:%d,next:%d\n",profit[i],cost[i],temp,sum,next);
                flag=true;
            }
        }
        if(!flag){
            return profit[start];
        }
        return sum;
    }
    private Map<Integer,Set<node>> map = new HashMap<>();
    public int getMaxScore(int[] x, int[] y, int[] cost, int[] profit) {
        // Write your code here
        for(int i=0;i<x.length;i++){
            if(map.containsKey(x[i])){
                map.get(x[i]).add(new node(y[i],cost[i]));
            }else {
                Set<node> set = new HashSet<>();
                set.add(new node(y[i],cost[i]));
                map.put(x[i],set);
            }
        }
        return getMaxScoreCore(profit,0);
    }
    public int getMaxScoreCore(int[] profit,int start){
        int sum=Integer.MIN_VALUE;
        if(map.containsKey(start)){
            Set<node> tempSet=map.get(start);
            for(node tempNode:tempSet){
                int tempInt = profit[start]-tempNode.getCost()+getMaxScoreCore(profit,tempNode.getEnd());
                sum=sum>=tempInt?sum:tempInt;
            }
        }else {
            return profit[start];
        }
        return sum;
    }
    class node{
        private int end;
        private int cost;
        public node(int end,int cost){
            this.end=end;
            this.cost=cost;
        }

        public int getEnd() {
            return end;
        }

        public int getCost() {
            return cost;
        }
    }
}
posted @ 2018-04-04 16:15  baixiaoshuai  阅读(196)  评论(0编辑  收藏  举报