# [BZOJ1564][NOI2009]二叉查找树

### [BZOJ1564][NOI2009]二叉查找树

#### 输入示例

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


#### 输出示例

29


#### 数据规模及约定

$n$ 开成 $110$ 足够了。

#### 题解

#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;
}

posted @ 2017-12-23 10:14  xjr01  阅读(133)  评论(0编辑  收藏  举报