Zoj 3820 Building Fire Stations The 2014 ACM-ICPC Asia Mudanjiang Regional Contest B Question tree diameter
Tree with n points, n-1 sides. Each side is 1. A fire station is built at two points to minimize the distance from other points to the fire station.
Idea: first find the tree diameter, and all vertices on the diameter are saved in an array. If the diameter is an odd number, delete the edge in the middle. If the diameter is an even number, divide the vertices in the middle
To the child tree on both sides. Calculate the midpoint of the tree diameter for the two subtree respectively. For details, see the code:
/*************************************** * ****************** File name: zoj3820.cpp author: kereo create time: ******************************** * ************************/# include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Include
# Define deusing namespace std; typedef long ll; const int sigma_size = 26; const int N = 100 + 50; const int MAXN = 200000 + 50; const int inf = 0x3fffffff; const double eps = 1e-8; const int mod = 1000000000 + 7; # define L (x) (x <1) # define R (x) (x <1 | 1) # define PII pair
# Define mk (x, y) make_pair (x), (y) int n, edge_cnt, top; int head [MAXN], vis [MAXN], d [MAXN], fa [MAXN], s [MAXN]; struct Edge {int v, next;} edge [MAXN <1]; void init () {edge_cnt = 0; memset (head,-1, sizeof (head);} void addedge (int u, int v) {edge [edge_cnt]. v = v; edge [edge_cnt]. next = head [u]; head [u] = edge_cnt ++;} int bfs (int st) {int ans = st; queue
Q; Q. push (st); vis [st] = 1; d [st] = 0; fa [st] =-1; while (! Q. empty () {int u = Q. front (); Q. pop (); for (int I = head [u]; I! =-1; I = edge [I]. next) {int v = edge [I]. v; if (vis [v]) continue; vis [v] = 1; d [v] = d [u] + 1; fa [v] = u; if (d [v]> d [ans]) ans = v; Q. push (v) ;}} top = 0; int u = ans; while (u! =-1) {s [top ++] = u; u = fa [u];} return ans;} int main () {// freopen ("in.txt ", "r", stdin); int T; scanf ("% d", & T); while (T --) {init (); scanf ("% d ", & n); for (int I = 1; I