【hihoCoder】Tower Defense Game

【题目】

微软FY16 Top Candidates 在线笔试

http://hihocoder.com/contest/mstest2015sept1/problem/3

由于比赛已过,也不知道下面代码对不对,欢迎讨论。


【代码】

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

class TreeNode {
	int level;
	int p;
	int q;
	List<TreeNode> children;
	
	public TreeNode(int level, int p, int q) {
		this.level = level;
		this.p = p;
		this.q = q;
		children = new ArrayList<TreeNode>();
	}
}

public class Main {
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		
		int n = in.nextInt();
		
		Map<Integer, TreeNode> map = new HashMap<Integer, TreeNode>();
		
		for (int i = 1; i <= n; i++) {
			int p = in.nextInt();
			int q = in.nextInt();
			
			TreeNode node = new TreeNode(i, p, q);
			map.put(i, node);
		}
		
		for (int i = 1; i < n; i++) {
			int a = in.nextInt();
			int b = in.nextInt();
			
			TreeNode root = map.get(a);
			TreeNode child = map.get(b);
			root.children.add(child);
		}
		
		TreeNode root = map.get(1);

		dfs(root);
		
		System.out.println(root.p);
	}
	
	public static void dfs(TreeNode root) {
		List<TreeNode> children = root.children;
		
		if (children.size() == 0) return;
		
		int sum = 0;
		int minRemain = Integer.MAX_VALUE;
		
		for (TreeNode child : children) {
			if (child.children.size() > 0) {
				dfs(child);
			}
			sum += child.p;
			sum -= child.q;
			minRemain = Math.min(minRemain, child.q);
		}
		
		sum += root.p;
		sum -= root.q;
		
		root.p = sum + minRemain;
		root.q = minRemain;
	}
}


你可能感兴趣的:(微软,DFS,hihoCoder)