小猴子要去拾桃子,走过一排数,每个树上有数量不等的桃子,小猴子只能在每颗树上拿一颗桃子,并且拿桃子的树不能比上一颗被拿桃子的树所结桃子数量少,求小猴子最多能拿多少颗桃子
输入 n+1行,第一行是有多少颗桃树,剩下行数分别是桃树所结桃子的个数
例如:
5
10
4
5
12
8
输出:
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 }
时间: 2024-10-16 14:07:16