zoukankan      html  css  js  c++  java
  • [BZOJ1564][NOI2009]二叉查找树

    [BZOJ1564][NOI2009]二叉查找树

    试题描述

    QAQ

    输入

    TAT

    输出

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

    输入示例

    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
    ", 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
    ", dp(1, n, 1));
    	
    	return 0;
    }
    
  • 相关阅读:
    任何时候都适用的20个C++技巧
    C++ 解析Json——jsoncpp(转)
    C++标准库和标准模板库(转)
    string标准C++中的的用法总结(转)
    JOIN US | 京东智联云诚聘技术精英
    在线公开课 | 云原生下的DevOps与持续交付
    AI端侧落地,京东AI技术如何部署边缘?
    CVPR 2020 | 京东AI研究院对视觉与语言的思考:从自洽、交互到共生
    IOT、AI、云计算等融合技术推进制造业产业转型
    边缘计算2.0时代,“云边缘”与“边缘云”你分清了吗?
  • 原文地址:https://www.cnblogs.com/xiao-ju-ruo-xjr/p/8092746.html
Copyright © 2011-2022 走看看