猿辅导笔试,第二题解法java(时间不够没提交,测试过了)

package 字符串; import java.util.*; public class Main { public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); int n = sc.nextInt();
        Map<Integer,List<Integer>> map = new HashMap<>(); int[] value = new int[n+2]; int[] dp = new int[n+2]; int[] dad = new int[n+2]; for (int i = 0; i < n; i++) { int val = sc.nextInt();  int father = sc.nextInt();
            value[i+2] = val;
            dp[i+2] = val;
            dad[i+2] = father;  if(map.containsKey(father)){
                List<Integer> list = map.get(father);
                list.add(i+2);
            }else{
                List<Integer> list = new ArrayList<>();
                list.add(i+2);
                map.put(father, list);
            }
        } for(Integer i:map.keySet()){ int pre = dp[i]; for(Integer j:map.get(i)){  if(dp[j] > 0) dp[i] += dp[j];
            } while(dp[i] > pre && dp[i]>0){ int father = dad[i]; if(father == 0) break;  int tmp = dp[father];  if(pre > 0){
                    dp[father] += (dp[i] - pre);
                }else{
                    dp[father] += dp[i];
                }
                i = father;
                pre = tmp;
            }
        } int max = Integer.MIN_VALUE; for (int i=0; i<n; i++){ if(dp[i+2] > max) max = dp[i+2];
        }
        System.out.println(max);
    }
} /* * 7 2 0 1 2 -1 2 2 3 -4 4 3 5 7 6 * */

#笔试题目##猿辅导#
全部评论
这个编辑器有毒。。。
点赞 回复 分享
发布于 2020-08-01 21:37

相关推荐

offer多多的六边形战士很无语:看了你的博客,感觉挺不错的,可以把你的访问量和粉丝数在简历里提一下,闪光点(仅个人意见)
点赞 评论 收藏
分享
专心打鱼:互联网搬运工,贴子都要偷
点赞 评论 收藏
分享
点赞 3 评论
分享
牛客网
牛客企业服务