博客
关于我
hdu6567 Cotree (树形dp 树的重心)
阅读量:249 次
发布时间:2019-03-01

本文共 1711 字,大约阅读时间需要 5 分钟。

Problem Description

Avin has two trees which are not connected. He asks you to add an edge between them to make them connected while minimizing the function

∑ni=1∑nj=i+1dis(i,j)
, where dis(i,j) represents the number of edges of the path from i to j. He is happy with only the function value.

Input

The first line contains a number n (2<=n<=100000). In each of the following n−2 lines, there are two numbers u and v, meaning that there is an edge between u and v. The input is guaranteed to contain exactly two trees.

Output

Just print the minimum function value.

Sample Input

3

1 2

Sample Output

4

思路:

树中所有点到某个点的距离和中,到重心的距离和是最小的;

如果有两个重心,那么他们的距离和一样

两次dfs树形dp找到两颗树的重心

把两个重心连接起来
再dfs树形dp一次计算答案

计算树上任意两点的距离和,转化为计算每条边被经过的次数乘上边权

每条边被经过的次数等于这条边分隔开
两端点分别所在的连通块的大小相乘
最后一次dfs树形dp的过程中
假设u是v的父节点,
以v为根的子树大小为sz[v]
则连接他们的边被经过的次数为(n-sz[v])*sz[v]

code:

#include
#include
#include
#include
#include
#include
#include
using namespace std;#define ll long longconst int inf=1e9;const int maxm=1e5+5;int head[maxm],nt[maxm<<1],to[maxm<<1],cnt;int mark[maxm];int sz[maxm],son[maxm];int num;//第一个连通块的大小int size;//第二个连通块的大小int root1,root2;int n;ll ans;void init(){ memset(head,0,sizeof head); memset(mark,0,sizeof mark); cnt=1; num=0; ans=0;}void add(int x,int y){ cnt++;nt[cnt]=head[x];head[x]=cnt;to[cnt]=y;}void dfs(int x){ num++;//计算连通块大小 sz[x]=1; son[x]=0; mark[x]=1; for(int i=head[x];i;i=nt[i]){ int v=to[i]; if(mark[v])continue; dfs(v); sz[x]+=sz[v]; son[x]=max(son[x],sz[v]); }}void dfs2(int x){ sz[x]=1; son[x]=0; mark[x]=1; for(int i=head[x];i;i=nt[i]){ int v=to[i]; if(mark[v])continue; dfs2(v); sz[x]+=sz[v]; son[x]=max(son[x],sz[v]); } son[x]=max(son[x],size-sz[x]); if(son[x]

转载地址:http://bnzv.baihongyu.com/

你可能感兴趣的文章
MaterialForm对tab页进行隐藏
查看>>
Member var and Static var.
查看>>
memcached高速缓存学习笔记001---memcached介绍和安装以及基本使用
查看>>
memcached高速缓存学习笔记003---利用JAVA程序操作memcached crud操作
查看>>
Memcached:Node.js 高性能缓存解决方案
查看>>
memcache、redis原理对比
查看>>
memset初始化高维数组为-1/0
查看>>
Metasploit CGI网关接口渗透测试实战
查看>>
Metasploit Web服务器渗透测试实战
查看>>
MFC模态对话框和非模态对话框
查看>>
Moment.js常见用法总结
查看>>
MongoDB出现Error parsing command line: unrecognised option ‘--fork‘ 的解决方法
查看>>
mxGraph改变图形大小重置overlay位置
查看>>
MongoDB可视化客户端管理工具之NoSQLbooster4mongo
查看>>
Mongodb学习总结(1)——常用NoSql数据库比较
查看>>
MongoDB学习笔记(8)--索引及优化索引
查看>>
mongodb定时备份数据库
查看>>
mppt算法详解-ChatGPT4o作答
查看>>
mpvue的使用(一)必要的开发环境
查看>>
MQ 重复消费如何解决?
查看>>