小猴子要去拾桃子,走過一排數,每一個樹上有數量不等的桃子,小猴子只能在每顆樹上拿一顆桃子,而且拿桃子的樹不能比上一顆被拿桃子的樹所結桃子數量少,求小猴子最多能拿多少顆桃子java
輸入 n+1行,第一行是有多少顆桃樹,剩下行數分別是桃樹所結桃子的個數node
例如:ui
5this
10spa
4code
5blog
12class
8import
輸出:二叉樹
4
5
8
回來晚了,剛寫完,平臺就關閉了,代碼沒怎麼驗證,貼出來,有問題請指出:
1 import java.util.*; 2 3 public class Main { 4 5 private static int maxRightCount = 0; 6 private static Node resultNode = null; 7 8 public static void main(String[] args) { 9 Scanner in = new Scanner(System.in); 10 int trees = Integer.parseInt(in.nextLine().trim()); 11 int[] peaches = new int[trees]; 12 for (int i = 0; i < peaches.length; i++) { 13 peaches[i] = Integer.parseInt(in.nextLine().trim()); 14 } 15 Node head = new Node(peaches[0]); 16 for (int i = 1; i < peaches.length; i++) { 17 buildBTree(peaches[i], head); 18 } 19 while (resultNode != null) { 20 System.out.println(resultNode.value); 21 resultNode = resultNode.right; 22 } 23 } 24 25 //構建二叉樹 26 private static void buildBTree(int value, Node node) { 27 if (value < node.value) { 28 if (node.left == null) { 29 node.left = new Node(value); 30 } else { 31 buildBTree(value, node.left); 32 } 33 } 34 if (value > node.value) { 35 node.rightCount++; 36 if (node.right == null) { 37 node.right = new Node(value); 38 if (node.rightCount > maxRightCount) { 39 maxRightCount = node.rightCount; 40 resultNode = node; 41 } 42 } else { 43 buildBTree(value, node.right); 44 } 45 } 46 } 47 48 49 private static class Node { 50 51 Node left; 52 Node right; 53 int value; 54 int rightCount; 55 56 Node(int value) { 57 this.value = value; 58 } 59 } 60 }