博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CF 1029E Tree with Small Distances
阅读量:4638 次
发布时间:2019-06-09

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

昨晚随便玩玩搞个div3结果浪翻了……

强烈谴责D题hack数据卡常

考虑到本题中所要求的最短距离不会大于2,所以我们可以把所有结点到$1$的距离通过对$3$取模分类,考虑到直接自顶向下贪心不满足局部最优解可以推出全局最优解,所以我们可以自下向上这样可以考虑到所有条件。我们处理出一个结点$x$所有儿子$y$的取模后的距离的最小值$dis$,那么一个结点向$1$连一条边的充要条件就是:

$dis == 0 && x != 1 && fa != 1$

时间复杂度$O(n)$。

Code:

#include 
#include
using namespace std;const int N = 2e5 + 5;int n, ans = 0, tot = 0, head[N];struct Edge { int to, nxt;} e[N << 1];inline void add(int from, int to) { e[++tot].to = to; e[tot].nxt = head[from]; head[from] = tot;}inline void read(int &X) { X = 0; char ch = 0; int op = 1; for(; ch > '9'|| ch < '0'; ch = getchar()) if(ch == '-') op = -1; for(; ch >= '0' && ch <= '9'; ch = getchar()) X = (X << 3) + (X << 1) + ch - 48; X *= op;}inline void chkMin(int &x, int y) { if(y < x) x = y;}int dfs(int x, int fat) { int dis = 2; for(int i = head[x]; i; i = e[i].nxt) { int y = e[i].to; if(y == fat) continue; chkMin(dis, dfs(y, x)); } if(dis == 0 && x != 1 && fat != 1) ans++; return (dis + 1) % 3;}int main() { read(n); for(int x, y, i = 1; i < n; i++) { read(x), read(y); add(x, y), add(y, x); } dfs(1, 0); printf("%d\n", ans); return 0;}
View Code

 

转载于:https://www.cnblogs.com/CzxingcHen/p/9532801.html

你可能感兴趣的文章
web渗透测试基本步骤
查看>>
使用Struts2标签遍历集合
查看>>
angular.isUndefined()
查看>>
第一次软件工程作业(改进版)
查看>>
WPF的图片操作效果(一):RenderTransform
查看>>
网络流24题-飞行员配对方案问题
查看>>
Jenkins 2.16.3默认没有Launch agent via Java Web Start,如何配置使用
查看>>
引入css的四种方式
查看>>
iOS开发UI篇—transframe属性(形变)
查看>>
3月7日 ArrayList集合
查看>>
jsp 环境配置记录
查看>>
Python03
查看>>
LOJ 2537 「PKUWC2018」Minimax
查看>>
使用java中replaceAll方法替换字符串中的反斜杠
查看>>
Android初学第36天
查看>>
Some configure
查看>>
json_encode时中文编码转正常状态
查看>>
流量调整和限流技术 【转载】
查看>>
Axure 全局辅助线(转)
查看>>
正由另一进程使用,因此该进程无法访问此文件。
查看>>