题目大意

给出一棵 \(n\) 个节点的树,删去其中两条边

使得分出的三个子树大小中最大与最小的差最小

分析

先一边 \(dfs\) 预处理出以 \(1\) 为根每个点的 \(size\)

然后按 \(dfs\) 的顺序枚举一个点,表示删去这个点返回父亲的边

记这个点为 \(x\)

分类讨论

第一种情况是删去当前点到根的一条边,记这条边下面的点为 \(y\)

这种情况会使子树 \(y\) 包含子树 \(x\)

第二种情况是删去不包含子树 \(x\) 的已经遍历过的边

这种情况须令外处理

于是我们算答案是要做两遍 \(dfs\)

具体细节看代码

\(Code\)

#include<cstdio>
#include<iostream>
#include<set>
using namespace std; const int N = 2e5 + 5;
int n, h[N], siz[N], ans;
set<int> s;
set<int>::iterator it;
struct edge{int to, nxt;}e[N << 1]; void add(int x, int y)
{
static int tot = 0;
e[++tot] = edge{y, h[x]}, h[x] = tot;
} void dfs(int x, int fa)
{
siz[x] = 1;
for(register int i = h[x], v; i; i = e[i].nxt)
{
v = e[i].to;
if (v == fa) continue;
dfs(v, x), siz[x] += siz[v];
}
} int getc(int x, int y, int z)
{
int a = max(max(x, y), z), b = min(min(x, y), z);
return a - b;
} void calc(int x)
{
int d = (n - siz[x]) >> 1;
it = s.lower_bound(d);
if (it != s.end()) ans = min(ans, getc(siz[x], *it, n - siz[x] - *it));
if (it != s.begin()) --it, ans = min(ans, getc(siz[x], *it, n - siz[x] - *it));
} void dfs1(int x, int fa)
{
calc(x);
s.insert(n - siz[x]);
for(register int i = h[x], v; i; i = e[i].nxt)
{
v = e[i].to;
if (v == fa) continue;
dfs1(v, x);
}
s.erase(n - siz[x]);
} void dfs2(int x, int fa)
{
for(register int i = h[x], v; i; i = e[i].nxt)
{
v = e[i].to;
if (v == fa) continue;
calc(v), dfs2(v, x);
}
s.insert(siz[x]);
} int main()
{
freopen("chilli.in", "r", stdin);
freopen("chilli.out", "w", stdout);
scanf("%d", &n);
for(register int i = 1, x, y; i < n; i++) scanf("%d%d", &x, &y), add(x, y), add(y, x);
ans = 0x3f3f3f3f, dfs(1, 0), dfs1(1, 0), s.clear(), dfs2(1, 0);
printf("%d", ans);
}

最新文章

  1. 室内定位系列(三)——位置指纹法的实现(KNN)
  2. Redhat/Ubuntu/Windows下安装Docker
  3. Android 常用抓包工具介绍之Charles
  4. Hadoop2.x源码-编译剖析
  5. Ubuntu14.04安装ROOT集群
  6. ubuntu修改源列表sourcelist的方法
  7. 深入理解jsavascript的作用域
  8. MSChart使用之动态生成多个多行ChartArea
  9. 网站集成QQ登录功能(转)
  10. number 类型转换 符号
  11. 【CJOJ1090】【洛谷1967】【NOIP2013】货车运输
  12. consul实现分布式锁
  13. NOIP-扫雷游戏
  14. part1:14-开发板介绍和开发板系统安装准备
  15. centos6安装最新syslog-ng推送hdfs
  16. hive对于lzo文件处理异常Caused by: java.io.IOException: Compressed length 842086665 exceeds max block size 67108864 (probably corrupt file)
  17. hihocoder #1388 : Periodic Signal fft
  18. (2.3)DDL增强功能-流程化控制与动态sql
  19. RabbitMQ---8、连接断开处理-断线重连
  20. MySQL几个特别语法示例

热门文章

  1. 关于python转义字符在正则匹配中的问题研究
  2. linux系统安装nginx中的subs-filter模块
  3. GO开发工具litelDE的安装与使用
  4. C++编程笔记(多线程学习)
  5. PyQt4编写界面的两种方式
  6. 12、synchronized和Lock的使用
  7. Python AI小项目打包通关:Pyinstaller和Wix都用上了
  8. CH432,CH438,CH9434串口扩展芯片常见问题
  9. 基于ERNIELayout&amp;pdfplumber-UIE的多方案学术论文信息抽取
  10. python之路27 单例模式实现方式、pickle模块、选课系统目录搭建