Problem: given a tree, color nodes black as many as possible without coloring two adjacent nodes
思路: 如果根节点r被标记为黑色,则其直接子节点不能被标记为黑色,如果不标记r,则其子节点可以标记为黑色,得到状态转移方程:
find(r) = max(black(r), white(r))
black(r)为当节点r被标记为黑色时,以r根节点的树中最多可标记为黑色的节点数
white(r)为当节点r不被标记为黑色时,以r根节点的树中最多可标记为黑色的节点数
则
white(r) = find(r.left) + find(r.right)
//当r没被标记为黑色时,对其左右子节点继续寻找
black(r) = 1 + whilte(r.left) + white(r.right)
//当r被标记为黑色时,它自身对总黑色节点数贡献1,然后它的左右子节点一定是非黑色节点
1 package com.self; 2 3 public class DP_03_Tree { 4 5 public static void main(String[] args) { 6 7 Node node4 = new Node(4); 8 Node node3 = new Node(3); 9 Node node5 = new Node(5); 10 Node node2 = new Node(2); 11 Node node1 = new Node(1); 12 13 node4.left = node3; 14 node4.right = node5; 15 node3.left = node2; 16 node3.right = node1; 17 18 DP_03_Tree app = new DP_03_Tree(); 19 int maxBlack = app.find(node4); 20 System.out.println(maxBlack); 21 } 22 23 int find(Node node){ 24 if(null == node) return 0; 25 if(null == node.left && null == node.right) return 1; 26 return Math.max(findFromWhite(node), findFromBlack(node)); 27 } 28 29 //Current node is white 30 int findFromWhite(Node node){ 31 if(null == node) return 0; 32 return find(node.left)+find(node.right); 33 } 34 35 //Current node is black 36 int findFromBlack(Node node){ 37 if(null == node) return 0; 38 //Current node is black, then its children do not count, but itself counts 39 return 1 + findFromWhite(node.left) + findFromWhite(node.right); 40 } 41 } 42 43 class Node{ 44 int v; 45 Node left; 46 Node right; 47 Node(int v){ 48 this.v = v; 49 } 50 }
时间: 2024-10-24 06:11:37