New Year Tree 我们假设当前的直径两端为A, B, 那么现在加入v的两个儿子x, y. 求直径的话我们可以第一次dfs找到最远点这个点必定为直径上的点, 然而用这个点第二次dfs找到最远点, 这两个点就是直径. 因为A, B现在是直径的两端, 那么从v点dfs找到的最远点必定为A或者B, 那么从 x dfs找到的最远点也必定为A或者B, 那么如果有 新的直径其中一个端点不会变, 当前图和原图的差别就是x和y, 那么比较dist(A, x), dist(B, x)和未加入前直径的长度就…
E. Anton and Tree time limit per test 3 seconds memory limit per test 256 megabytes input standard input output standard output Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph. There are n v…
http://lightoj.com/volume_showproblem.php?problem=1094 Given a tree (a connected graph with no cycles), you have to find the farthest nodes in the tree. The edges of the tree are weighted and undirected. That means you have to find two nodes in the t…
F. New Year Tree time limit per test2 seconds memory limit per test256 megabytes You are a programmer and you have a New Year Tree (not the traditional fur tree, though) - a tree of four vertices: one vertex of degree three (has number 1), connected…
Codeforces 题目传送门 & 洛谷题目传送门 其实是一道还算一般的题罢--大概是最近刷长链剖分,被某道长链剖分与直径结合的题爆踩之后就点开了这题. 本题的难点就在于看出一个性质:最长路径的其中一个端点一定是直径的某一个端点. 证明:首先我们找出原树的一个直径,如果直径上标记边的个数为偶数那显然这条直径就是最优解,符合题意,否则我们假设我们找出的直径为 \(AB\),我们已经找出了一条符合要求的路径 \(CD\),下证我们总可以通过调整 \(CD\) 的端点,找出一条以 \(A\) 或 \…
题目描述 给定一棵N个点的树,求树上一条链使得链的长度乘链上所有点中的最小权值所得的积最大. 其中链长度定义为链上点的个数. 输入 第一行N 第二行N个数分别表示1~N的点权v[i] 接下来N-1行每行两个数x.y,表示一条连接x和y的边 输出 一个数,表示最大的痛苦程度. 样例输入 3 5 3 5 1 2 1 3 样例输出 10 题解 树的直径+并查集 首先肯定是把权值从大到小排序,按照顺序加点,维护每个连通块的最长链乘以当前点权值作为贡献. 那么如何在加上一条边,连接两棵树后快速得出新的直径…
题目大意: 给定一棵有n个节点的树,有黑点白点两种节点. 每一次操作可以选择一个同种颜色的联通块将其染成同一种颜色 现在给定一个初始局面问最少多少步可以让树变为纯色. 题解: 首先我们拿到这棵树时先将其缩点 然后我们手中的树就变成了一棵黑白相间的黑白树. 那么我们现在就是每次选择一个节点使其变色,都会使得这个节点相邻的所有节点合并进来. 所以我们找度数最大的合并就好了啊 我们现在把这棵树想象成由若干条路径组成的. 那么我们每次合并都会使某些路径的长度最多减少2 所以我们可以自然而然地想到一定是树…
D. Two Paths time limit per test 2 seconds memory limit per test 64 megabytes input standard input output standard output As you know, Bob's brother lives in Flatland. In Flatland there are n cities, connected by n - 1 two-way roads. The cities are n…
To your surprise, Jamie is the final boss! Ehehehe. Jamie has given you a tree with n vertices, numbered from 1 to n. Initially, the root of the tree is the vertex with number 1. Also, each vertex has a value on it. Jamie also gives you three types o…
可以证明,如果合并两棵树,新的直径的端点一定是原来两树中直径的端点 可以把新加两个点的操作看成是把两个只有一个点的树合并到原来的树上,然后用其中的一个点去和原来树上的直径两端点更新直径就可以了 #include<bits/stdc++.h> #define pa pair<int,int> #define CLR(a,x) memset(a,x,sizeof(a)) using namespace std; typedef long long ll; ; inline ll rd(…