BST最優二叉檢索樹(java版本)

來源:互聯網
上載者:User

標籤:

這個內容是去年暑假講的,但是一直沒有實現,

其實說白了就是區間dp,求一個序列構成二叉樹,中序遍曆有序.

核心和其他區間dp一樣,枚舉中間值.然後枚舉出來後再將整個區間的機率累加,因為相當於加深了一層.

JAVA代碼,附測試資料

import java.util.Arrays;import java.util.Scanner;public class Main {/** * 輸入p: 訪問機率數組; 0,1,....n是排好序的Key值 * 輸出A=new float[n][n]: 最優時間矩陣 * 輸出R=new int[n][n]: 根結點矩陣 * @param p * @param A * @param R */static void optimalBST(double[] p, double[][] A, int[][] R) {int n = p.length;Arrays.sort(p);for (int i = 0; i < n; i++) {A[i][i] = p[i];R[i][i] = i; // the root is itself}for (int len = 1; len < n; len++) {for (int st = 0; st + len < n; st++) {int ed = st + len;int root = st;double min = Double.MAX_VALUE;for (int k = st; k <= ed; k++) {double tmp;if (k == st)tmp = A[k + 1][ed];else if (k == ed)tmp = A[st][k - 1];elsetmp = A[k + 1][ed] + A[st][k - 1];if (min > tmp) {min = tmp;root = k;}}R[st][ed] = root;A[st][ed] = min;for (int i = st; i <= ed; i++)A[st][ed] += p[i];}}}public static void print(int st,int ed,int [][] R){if(st==ed) {System.out.print(R[st][ed]);return;}System.out.print("(");print(st,R[st][ed]-1,R);System.out.print(")");System.out.print(R[st][ed]);System.out.print("(");print(R[st][ed]+1,ed,R);System.out.print(")");}public static void main(String[] args) {//Scanner input = new Scanner(System.in);double [][] A = new double[5][5];int [][] R = new int[5][5];//optimalBST1(new double [] {0.15, 0.10,0.05,0.10,0.20},A,R);//System.out.println(A[0][4]);//print(0,4,R);optimalBST(new double [] {0.15, 0.10,0.05,0.10,0.20},A,R);System.out.println(A[0][4]);print(0,4,R);}}


BST最優二叉檢索樹(java版本)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.