UVA10304 Optimal Binary Search Tree最优排序二叉树

Posted 海岛Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA10304 Optimal Binary Search Tree最优排序二叉树相关的知识,希望对你有一定的参考价值。

Given a set S = (e1, e2, …, en) of n distinct elements such that e1 < e2 < . . . < en and considering a binary search tree (see the previous problem) of the elements of S, it is desired that higher the query frequency of an element, closer will it be to the root.
    The cost of accessing an element ei of S in a tree (cost(ei)) is equal to the number of edges in the path that connects the root with the node that contains the element. Given the query frequencies of the elements of S, (f(e1), f(e2), . . . , f(en)), we say that the total cost of a tree is the following summation:
f(e1) ∗ cost(e1) + f(e2) ∗ cost(e2) + . . . + f(en) ∗ cost(en)
    In this manner, the tree with the lowest total cost is the one with the best representation for searching elements of S. Because of this, it is called the Optimal Binary Search Tree.
Input
The input will contain several instances, one per line.
    Each line will start with a number 1 ≤ n ≤ 250, indicating the size of S. Following n, in the same line, there will be n non-negative integers representing the query frequencies of the elements of S: f(e1), f(e2), . . . , f(en), 0 ≤ f(ei) ≤ 100. Input is terminated by end of file.
Output
For each instance of the input, you must print a line in the output with the total cost of the Optimal Binary Search Tree.
Sample Input
1 5
3 10 10 10
3 5 10 20
Sample Output
0
20
20

问题链接UVA10304 Optimal Binary Search Tree
问题简述:(略)
问题分析:最优排序二叉树(OBST)问题,不解释。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA10304 Optimal Binary Search Tree */

#include <bits/stdc++.h>

using namespace std;

const int INF = 0x3F3F3F3F;
const int N = 250 + 1;
int a[N], sum[N], dp[N][N];

int main()
{
    int n;
    while (scanf("%d", &n) == 1) {
        sum[0] = 0;
        for (int i = 1; i <= n; i++) {
            scanf("%d", &a[i]);
            sum[i] = sum[i - 1] + a[i];
        }

        memset(dp, 0, sizeof dp);
        for (int d = 2; d <= n; d++)
            for (int l = 1; l <= n - d + 1; l++) {
                int r = l + d - 1;
                int tot = sum[r] - sum[l - 1];
                int ans = INF;
                for (int k = l; k <= r; k++)
                    ans = min(ans, dp[l][k - 1] + dp[k + 1][r] + tot - a[k]);
                dp[l][r] = ans;
            }

        printf("%d\\n", dp[1][n]);
    }

    return 0;
}

以上是关于UVA10304 Optimal Binary Search Tree最优排序二叉树的主要内容,如果未能解决你的问题,请参考以下文章

uva 10304 - Optimal Binary Search Tree 区间dp

uva10304-最优排序二叉树

uva1349Optimal Bus Route Design

ITA 15.5 Optimal binary search trees

[Coding Made Simple] Optimal Binary Search Tree

UVA1349 Optimal Bus Route Design 拆点法+最小费用最佳匹配