1. 二叉排序树直径,给一数组,求生成的二叉排序树的最大直径,直径:过根节点的最长链的长度。 AC
IN:
7
5 3 2 1 6 7 4
OUT:
6
import java.util.Scanner; public class Main1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } System.out.println(help(arr)); } private static long help(int[] arr) { Node root = new Node(arr[0]); for (int i = 1; i < arr.length; i++) { insert(root, arr[i]); } long left = depth(root.left); long right = depth(root.right); return left + right + 1; } private static long depth(Node root) { if (root == null) return 0; long maxLeft = depth(root.left); long maxRigth = depth(root.right); return Math.max(maxLeft, maxRigth) + 1; } private static void insert(Node root, int val) { if (root == null) return; if (val < root.val) { if (root.left != null) { insert(root.left, val); return; } else { root.left = new Node(val); return; } } if (val > root.val) { if (root.right != null) { insert(root.right, val); } else { root.right = new Node(val); } } } } class Node { int val; long level; Node left; Node right; public Node() { } public Node(int val) { this.val = val; } public Node(int val, long level) { this.val = val; this.level = level; } }2. 2题结果不对。。求指错
n男生,m女生,组k合唱团,男生至少3个,女生至少2个,求组合种数。
import java.util.Scanner; public class Main2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); // 男 int m = in.nextInt(); // 女 int k = in.nextInt(); // k个同学的歌唱队,至少3男 2女; System.out.println(help(n, m, k)); } private static long help(int n, int m, int k) { int mod = 1000000007; if (n < 3 || m < 2) return 0; if (n + m < k) return 0; if (n == 3) return composite(m, k - n) % mod; if (m == 2) return composite(n, k - m) % mod; long res = 0L; for (int i = 3; i < k - 2; i++) { int girl = k - i; if (girl < 2) { break; } res += composite(n, i) * composite(m, girl); } return res % mod; } private static long composite(int n, int k) { long result = 1L; for (int i = k; i > 0; i--) { result *= n; n--; } for (int i = 1; i <= k; i++) { result = result / i; } return result; } }
全部评论
(0) 回帖