码迷,mamicode.com
首页 > 其他好文 > 详细

[BZOJ1564][NOI2009]二叉查找树

时间:2017-12-23 14:10:24      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:stream   ++   --   type   int   中序   bool   while   string   

[BZOJ1564][NOI2009]二叉查找树

试题描述

技术分享图片

输入

技术分享图片

输出

只有一个数字,即你所能得到的整棵树的访问代价与额外修改代价之和的最小值。

输入示例

4 10
1 2 3 4
1 2 3 4
1 2 3 4

输出示例

29

数据规模及约定

\(n\) 开成 \(110\) 足够了。

题解

先将节点按照中序遍历(即数据值升序)排好,把权值离散一下,然后可以设计 dp 了。令 \(f(l, r, k)\) 表示对于区间 \([l, r]\) 中的节点,权值都不小于 \(k\) 的最小访问代价。那么转移就是枚举哪个点作为根节点,然后看它是否需要改动权值,是要改大还是改小。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;
#define rep(i, s, t) for(int i = (s); i <= (t); i++)
#define dwn(i, s, t) for(int i = (s); i >= (t); i--)

int read() {
    int x = 0, f = 1; char c = getchar();
    while(!isdigit(c)){ if(c == ‘-‘) f = -1; c = getchar(); }
    while(isdigit(c)){ x = x * 10 + c - ‘0‘; c = getchar(); }
    return x * f;
}

#define maxn 110
#define oo 2147483647

struct Node {
    int key, val, freq;
    Node() {}
    Node(int _1, int _2, int _3): key(_1), val(_2), freq(_3) {}
    bool operator < (const Node &t) const { return key < t.key; }
} ns[maxn];
int n, K, num[maxn], f[maxn][maxn][maxn];

int dp(int l, int r, int lo) {
    if(l == r) return ns[l].freq + K * (ns[l].val < lo);
    if(l > r) return 0;
    if(f[l][r][lo] < oo) return f[l][r][lo];
    int sum = 0;
    rep(i, l, r) sum += ns[i].freq;
    rep(i, l, r)
        f[l][r][lo] = min(f[l][r][lo], dp(l, i - 1, max(lo, ns[i].val + 1)) + dp(i + 1, r, max(lo, ns[i].val + 1)) + sum + K * (ns[i].val < lo)),
        f[l][r][lo] = min(f[l][r][lo], dp(l, i - 1, lo) + dp(i + 1, r, lo) + sum + K * (ns[i].val != lo));
    // printf("f[%d][%d][%d] = %d\n", l, r, lo, f[l][r][lo]);
    return f[l][r][lo];
}

int main() {
    n = read(); K = read();
    rep(i, 1, n) ns[i].key = read();
    rep(i, 1, n) num[i] = ns[i].val = read(); num[n+1] = oo;
    rep(i, 1, n) ns[i].freq = read();
    sort(ns + 1, ns + n + 1);
    
    rep(i, 1, n) rep(j, 1, n) rep(k, 1, n + 1) f[i][j][k] = oo;
    sort(num + 1, num + n + 1);
    rep(i, 1, n) ns[i].val = lower_bound(num + 1, num + n + 2, ns[i].val) - num;
    
    printf("%d\n", dp(1, n, 1));
    
    return 0;
}

[BZOJ1564][NOI2009]二叉查找树

标签:stream   ++   --   type   int   中序   bool   while   string   

原文地址:http://www.cnblogs.com/xiao-ju-ruo-xjr/p/8092746.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!