bzoj3257 树的难题(树形dp)

Summary ATP感觉自己退役之前是用不上机房的空调了【笑 阅读详情

dp[x][i][j]表示以x为根的子树,与x相连的有i个黑点,j个白点,其他的点都满足要求的最小代价。超过1个的黑点视作1个,超过2个的白点视作2个。每次转移用已经做过的儿子们的状态和现在儿子的状态,注意不能像背包那样往上叠加,因为不可以不取现在这个儿子。然后对于当前这个儿子无非两种决策:连在x上,断掉。如果断掉,必须满足儿子的状态是均衡的,即!i||j<2。别忘了每次把x自己的颜色加上。最后答案就是整棵树均衡状态的最小值。复杂度O(n)

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define ll long long
#define inf 1LL<<60
#define N 300010
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
    return x*f;
}
int n,a[N],h[N],num=0,fa[N];
ll dp[N][2][3],tmp[2][3];//dp[x][i][j],以x为根的子树,与x相连的有i个黑点,j个白点的最小代价
struct edge{
    int to,next,val;
}data[N<<1];
inline void dfs(int x){
    for(int i=0;i<2;++i)
        for(int j=0;j<3;++j) dp[x][i][j]=inf;dp[x][a[x]==0][a[x]==1]=0;
    for(int o=h[x];o;o=data[o].next){
        int y=data[o].to;if(y==fa[x]) continue;
        fa[y]=x;dfs(y);
        for(int i=0;i<2;++i) for(int j=0;j<3;++j) tmp[i][j]=inf;
        for(int i=0;i<2;++i)
            for(int j=0;j<3;++j){
                if(dp[x][i][j]==inf) continue;
                for(int ii=0;ii<2;++ii)
                    for(int jj=0;jj<3;++jj){
                        if(dp[y][ii][jj]==inf) continue;
                        int i1=i+ii>1?1:i+ii,j1=j+jj>2?2:j+jj;
                        tmp[i1][j1]=min(tmp[i1][j1],dp[x][i][j]+dp[y][ii][jj]);
                        if(!ii||jj<2) tmp[i][j]=min(tmp[i][j],dp[x][i][j]+dp[y][ii][jj]+data[o].val);
                    }
            }memcpy(dp[x],tmp,sizeof(tmp));
    }
}
int main(){
//  freopen("a.in","r",stdin);
    int tst=read();
    while(tst--){
        n=read();memset(h,0,sizeof(h));num=0;ll ans=inf;
        for(int i=1;i<=n;++i) a[i]=read();
        for(int i=1;i<n;++i){
            int x=read(),y=read(),val=read();
            data[++num].to=y;data[num].next=h[x];h[x]=num;data[num].val=val;
            data[++num].to=x;data[num].next=h[y];h[y]=num;data[num].val=val;
        }dfs(1);
        for(int i=0;i<2;++i)
            for(int j=0;j<3;++j)
                if(!i||j<2) ans=min(ans,dp[1][i][j]);
        printf("%lld\n",ans);
    }return 0;
}
树形dp问题总结(转发) 关于树形dp问题做题之后的总结,有题目,有代码,有总结。 立即下载

相关推荐

概率dp 树形dp经典题目加解析

概率dp 树形dp经典题目加解析........高斯求期望...............

[BZOJ]3257树的难题 树型DP

dp[v][0/1][0/1/2]表示dp到v点,与v联通的一块没有黑点/有黑点,没有白点/有一个白点/有很多白点所需最小代价。考虑v与其儿子的边删还是不删转移就可以了。 这个好复杂,其实令dp[i][0/1/2]表示以i为根的子树中,满足题目要求且i所在的联通块是无黑色点/无白色点/有一个白色点的边权和最小值。 转移应当十分显然。 令u为i的其中一个儿子,len为连接u,i的边权+dp[u]

DOFYPXY的博客 541

NHANES数据库的介绍及使用(一)

一、数据库概况 NHANES(National Health and Nutrition Examination Survey)是一项旨在评估美国成人和儿童健康和营养状况的研究计划,计划始于20世纪60年代初期,是一项针对不同人群或健康主题的调查。 1999年该调查成为一项持续计划,涉及各种健康和营养测量,项目每年调查一个全国代表性的样本,约5000人,这些人群位于全国各县,每年对其中15个县进行访问。 NHANES访谈部分包括人口统计学、社会经济学、饮食和健康相关问题。体检部分包括生理测量、实验室检查等

Christina 5万+

BZOJ3257 : 树的难题

设$f[x][i][j]$表示以$x$为根的子树,与$x$连通部分有$i$个黑点,$j$个白点,不联通部分都是均衡的最小代价。若$i&gt;1$,则视作$1$;若$j&gt;2$,则视作$2$。 然后进行树形DP即可,转移的时候如果不要那棵子树,那么那棵子树的状态必须满足$!i||j&lt;2$。 时间复杂度$O(n)$。   #include&lt;cstdio&gt; #defi...

weixin_33705053的博客 151

双目视觉入门实战:用Matlab标定相机,再到Python OpenCV完成测距的完整链路

本文详细介绍了双目视觉技术的完整实现流程,从Matlab相机标定到Python OpenCV测距的全链路实践。重点解析了Matlab与OpenCV的参数转换技巧,以及立体校正、视差计算等关键步骤的代码实现,帮助开发者快速掌握双目测距系统的搭建方法。

weixin_29166013的博客 436

如何正确理解和获取S参数

差分四端口的S参数是由双端口S参数逐步演化而来,因此,在数学中,其各分量均可以从单端S参数推导而来,在实际的仿真和测试中,软件和测量设备也是通过获取单端S参数矩阵再进行运算得到混合S参数矩阵的,并非直接获取。

一只豌豆象的博客 5138

bzoj3257: 树的难题

题目链接 bzoj3257: 树的难题 题解 dp一下 代码 #include<cstdio> #include<cstring> #include<algorithm> inline int read() { int x = 0,f = 1; char c = getchar(); while(c < '0'...

agtvo48266的专栏 162

【原创】关于西门子S120 的电气图纸设计

我们首先要了解一下模块的基本信息:SINAMICS 功率模块 PM240-2 三相交流380-480V+10/-10% 47-63Hz;至此,我们选择的驱动系统配置的资料都已经查找完毕,接下来就是根据每个部件的功能接口和我们需要实现的功能画出接线连接图,这样关于伺服电机控制,硬件部分设计就完成了。2)FSA - FSC 型功率模块 PM240-2 的屏蔽连接板外形尺寸图,所有数据以毫米(英寸)为单位。1)FSA 型功率模块 PM240-2 的外形尺寸图,所有数据以毫米(英寸)为单位。

Qinmingyue13的博客 2632

bzoj3257 树的难题(树形DP)

Description 给出一个无根树。树有N个点,边有权值。每个点都有颜色,是黑色、白色、 灰色这三种颜色之一,称为一棵三色树。 可爱的 Alice觉得,一个三色树为均衡的,当且仅当,树中不含有黑色结点 或者含有至多一个白色节点。然而,给出的三色树可能并不满足这个性质。 所以,Alice打算删去若干条边使得形成的森林中每棵树都是均衡的,花费 的代价等于删去的边的权值之和。请你计算需要花费的代价最...

逝者如斯夫,不舍昼夜 615

吊打BEVFormer!GaussianBeV实战:用3D高斯开启BEV分割新范式

GaussianBeV是一种基于3D高斯建模的BEV分割新方法,在自动驾驶感知任务中实现了SOTA性能。其核心创新在于将场景元素表示为3D高斯分布,通过均值、协方差和权重精确描述物体位置、形状和置信度,相比传统BEV方法具有更强的空间建模能力。文章详细介绍了GaussianBeV的原理、环境配置、训练推理流程及其在自动驾驶和城市3D重建中的应用,并讨论了优化方向和未来发展趋势。该方法在nuScenes等数据集上表现出色,为BEV分割任务提供了新的解决方案。

m0_71589036的博客 102

RK3588 C++ MeloTTS 推理

本文介绍了基于RK3588平台和RKNN工具链实现的端侧语音合成(TTS)系统。该系统支持中英文混合输入处理,通过自动合并英文单词、转换标点符号等方式预处理文本,并将其转换为音素和声调序列。核心推理流程包含编码器、中间处理和解码器三个阶段:编码器将音素序列转为隐藏状态,中间处理调节音调和语速,解码器生成最终波形。代码示例展示了输入数据设置和模型推理过程,利用RK3588内置NPU实现高效语音合成。该系统展现了在边缘计算设备上实现复杂AI任务的能力。

J。 194

[BZOJ 3257]树的难题

树形DP

_Horizon 1918

反爬虫:对抗最新反爬技术 Cloudflare详解

本文针对Cloudflare最新反爬机制提供完整解决方案,覆盖TLS指纹、行为轨迹、设备指纹等检测场景。文章首先分析Cloudflare的三重检测体系(TLS指纹、行为指纹、设备指纹)及其拦截表现,随后提出四种绕过方案:1)使用curl_cffi模拟浏览器TLS指纹;2)通过undetected-chromedriver移除自动化特征;3)Playwright结合stealth插件模拟人类行为;4)动态请求调度策略。重点推荐轻量级Python方案curl_cffi和浏览器自动化方案Playwright-st

数据知道的博客 4614

[bzoj 3257][jzoj 3347] 树的难题 {拓扑排序+树形dp}

题目 https://www.lydsy.com/JudgeOnline/problem.php?id=3257 解题思路 设f[x]f[x]f[x]表示以xxx为根的子树中,满足有0个黑色点,若干个白色点的最少切割次数;g[x]g[x]g[x]表示以xxx为根的子树中,满足有若干个黑色点,0个白色点的最少切割次数;h[x]h[x]h[x]表示以xxx为根的子树中,满足有若干个黑色点,1个白色点...

Nowed 561

LabVIEW实现TCP通信

在本节中,我们将简要探讨TCP通信的基础知识,并以工业物联网平台TLINK中的云端设备数据发布设计为例,详细阐述在互联网环境下TCP客户端应用程序设计的基本方法。

不脱发的程序猿 1947

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

jzoj3347,bzoj3257-[NOI2013模拟]树的难题【树形dp】

正题 BZOJBZOJBZOJ题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=3257 题目大意 一棵树上的节点有333种颜色,有边权。 选择一些边割掉使得森林中每棵树只有一个白点或没有黑点。 求割掉的边的最小值。 解题思路 定义fi,statef_{i,state}fi,state​表示iii的子树中割掉后森林所有的树都满足条件且目...

QuantAsk 563

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

BZOJ.3257.树的难题(树形DP)

题目链接 状态只与黑、白两点的颜色有关,于是用 \(f[x][i][j]\)表示当前以x为根节点,有\(i\)个黑点\(j\)个白点,使得x子树满足该条件的最小花费。 最后答案就是 \(min\{f[root][0][j],f[root][i][0/1]\}\)。 把 \(i\geq 1\)的状态都看做 \(i=1\),\(j\geq 2\)的状态都看做 \(j=2\). 更新顺序同树上背包一样,...

weixin_30819163的博客 191

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【题解】BZOJ3257:树的难题

原题传送门 这真是一道难题qwq 看了%%%Claris的题解后懂了 树形DP 先设置状态,dp[u][i][j]dp[u][i][j]dp[u][i][j]表示以u为根的子树中黑点iii个,白点jjj个,的答案 首先优化空间,i&gt;=1i&gt;=1i>=1的情况等价于i=1i=1i=1,反正都是不满足要求的 j&gt;=2j&gt;=2j>=2的...

ModestCoder_的博客 599

bzoj3257 树的难题

http://www.elijahqi.win/2018/01/14/bzoj3257-%e6%a0%91%e7%9a%84%e9%9a%be%e9%a2%98/ Description 给出一个无根树。树有N个点,边有权值。每个点都有颜色,是黑色、白色、 灰色这三种颜色之一,称为一棵三色树。 可爱的 Alice觉得,一个三色树为均衡的,当且仅当,树中不含有黑色结点 或者含有至多一个白色

Elijahqi 525

BZOJ 3257: 树的难题

树形DP #include<cstdio> #include<algorithm> #define rep(i,x,y) for (int i=x; i<=y; i++) using namespace std; int cnt,last[300005],c[300005]; long long F[300005][2][3],G[2][3]; st...

weixin_33862514的博客 138

[2016-3-15 Test]

题目总结

_Horizon 483

DP泛做

DP泛做[CF455 A] Boredom题目大意给定n个数,每次任选一个数ai,得到ai的得分,同时ai−1和ai+1都消失,无法再被选取,询问最大得分和给定n个数,每次任选一个数a_i,得到a_i的得分,同时a_i-1和a_i+1都消失,无法再被选取,询问最大得分和题解dp[i,1]:[1,i]的数都被处理完,i这个数被选的最大得分和dp[i,1]:[1,i]的数都被处理完,i这个数被选的最大得

slongle的专栏 892

2019.07.10【NOIP提高组】模拟 A 组

解题报告BZOJ 3257 JZOJ 3347 树的难题分析代码BZOJ 3258 JZOJ 3348 秘密任务分析代码JZOJ 3379 查询题目分析代码 BZOJ 3257 JZOJ 3347 树的难题 题目 分析 树形dp,设dp[x][i][j]dp[x][i][j]dp[x][i][j]表示第xxx个点,有无黑点,白点个数为jjj,若j≥2j\geq 2j≥2视作2的最小代价 那么dp...

lemondinosaur的博客 375

暑期十测 round1

day1day1: 组合数:水题。。。直接上杨辉三角。 构造回文字符串:区间dp、最长公共子序列两种写法。对dp又有了进一步的认识。 最长回文:manacharmanachar模板题(此模板真好背)。 day2day2: 我要的幸福:bfsbfs乱搞,先把小的添加进队列。 组合字符串:记忆化搜索。 行程得分:dp待填坑。 day3day3: 天黑黑:用栈模拟二叉树,再贪心。 找字

Donald_TY的专栏 536
上一篇: bzoj3064 Tyvj 1518 CPU监控(线段树维护历史最值)
下一篇: bzoj3058 四叶草魔杖(状压dp+最小生成树)
Icefox_zhx
博客等级 码龄10年 81粉丝 1239原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值