【b303】加分二叉树

【题目链接】:https://vijos.org/p/1100

【题意】

【题解】

因为已经确定了最后中序遍历的结果为1..n;
所以对于每一个区间[l..r]
你需要确定这个区间里面哪一个是这个子树的根节点root

[l..root-1]和[root+1..r]分别为它的左子树和右子树
可以想见这是一个重复的过程
枚举这段区间的根节点是什么;
然后获取l..root-1和root+1..r的加分
乘起来然后再加上a[root],看看是不是比f[l][r]更优.
写个DP就好;
(中序的话确定根节点之后,左右子树就能确定了);

【完整代码】

#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%lld",&x)

typedef pair<int, int> pii;
typedef pair<LL, LL> pll;

const int dx[9] = { 0,1,-1,0,0,-1,-1,1,1 };
const int dy[9] = { 0,0,0,-1,1,-1,1,-1,1 };
const double pi = acos(-1.0);
const int N = 40;

int n,gen[N][N];
LL a[N];
bool bo[N][N];
LL f[N][N];
vector<int> ans;

void dfs2(int x, int y)
{
    if (x > y) return;
    if (x == y)
        return ans.push_back(x);
    rep1(i, x, y)
    {
        LL A = f[x][i - 1], B = f[i + 1][y];
        if (A == 0) A = 1;
        if (B == 0) B = 1;
        if (A*B + a[i] == f[x][y])
        {
            ans.push_back(i);
            dfs2(x, i - 1);
            dfs2(i + 1, y);
            return;
        }
    }
}

int main()
{
    //freopen("F:\rush.txt", "r", stdin);
    rei(n);
    rep1(i, 1, n)
        rel(a[i]);
    rep1(i, 1, n)
        f[i][i] = a[i];
    rep1(i, 2, n)
        f[i-1][i] = a[i] + a[i - 1];
    rep1(l,3,n)
        rep1(i, 1, n)
        {
            int ii = i + l - 1;
            if (ii > n) break;
            rep1(j, i, ii)
            {
                LL A = f[i][j - 1], B = f[j + 1][ii];
                if (A == 0) A = 1;
                if (B == 0) B = 1;
                f[i][ii] = max(f[i][ii], A * B + a[j]);
            }
        }
    cout << f[1][n] << endl;
    dfs2(1, n);
    int len = ans.size();
    rep1(i, 0, len - 1)
    {
        printf("%d", ans[i]);
        if (i == len - 1)
            puts("");
        else
            putchar(' ');
    }
    return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/7626568.html