UVA 10304 - Optimal Binary Search Tree

这道题以二叉搜索树为背景,有点像最优矩阵链乘的问题:

设f[i][j] 表示元素i到元素j的最优解,设k为i到j元素所形成二叉树的根,则有f[i][j] = min{f[i][k-1]+f[k+1][j]+sum[i][j]-a[k]},这里sum[i][j]为i到j的查找频率之和,a[k]为root的查找频率,因此我们要求所有元素的前缀和,为什么要加sum[i][j]-a[k];因为我们每加一层,相当于加了sum[i][j]-a[k];

代码如下;

#include<stdio.h>

#include<string.h>

#define MAXN 260

#define INF 1000000000

int N, d[MAXN], f[MAXN][MAXN], a[MAXN], A[MAXN];

void init()

{

    int i, j;

    for(i = 1; i <= N; i ++)

        scanf("%d",&a[i]);

        A[0] = 0;

        for(i = 1; i <= N; i ++)

            A[i] = A[i-1] + a[i];

}

void solve()

{

    int i, j, k, temp;

    for(i = 1; i <= N; i ++)

        f[i][i-1] = f[i+1][i] = 0;

    for(i = 1; i <= N; i ++)

        for(j = i; j <= N; j ++)

            f[i][j] = INF;

    for(k = 0; k < N; k ++)

        for(i = 1; i + k <= N; i ++)

            for(j = i; j <= i+k; j ++)

            {

                temp = f[i][j - 1] + f[j+1][i+k]+A[i+k]-A[i-1]-a[j];

                if(temp < f[i][i+k])

                    f[i][i+k] = temp;

            }

        printf("%d\n",f[1][N]);

}

int main()

{

    while(scanf("%d",&N) == 1)

    {

        init();

        solve();

    }

    return 0;

}

 

你可能感兴趣的:(Binary search)