For a tree, you need to find two points so that the distance between all points is the maximum value of a point that is closer to you. (the result of all points is the maximum value, that is, the maximum distance) is the smallest. The meaning should be clear.
Solution: Consider setting the tree as follows:
Then we can delete the diameter edge in the middle and find a center of diameter in the two sub-trees. Then these two points can be used as the answer. At that time, I thought this was correct, but it cannot be proved.
As a result, several BFS can be done.
At that time, I wrote TLE because I used Map <pair <int, int>, int> to save the edge to be deleted. After that, I couldn't get rid of it. map should be used as little as possible.
Code:
# Include <iostream> # include <cstdio> # include <cstring> # include <cstdlib> # include <cmath> # include <algorithm> # include <string> # include <vector> # include <queue> using namespace STD; # define n 200007int vis [N], Fa [N]; int Maxi, maxtag; struct node {int DIS, u ;}; vector <int> G [N]; int U, V; void BFS (INT s) {node now; now. U = s; now. dis = 0; Maxi = 0, maxtag = s; queue <node> que; Fa [s] =-1; memset (VIS, 0, sizeof (VI S); Que. Push (now); vis [s] = 1; while (! Que. empty () {node TMP = que. front (); que. pop (); int Dis = TMP. DIS; int u = TMP. u; If (DIS> Maxi) // The farthest point Maxi = DIS, maxtag = u; For (INT I = 0; I <G [u]. size (); I ++) {int v = G [u] [I]; If (vis [v]) continue; if (u = u & V = V) | (u = V & V = u) continue; now. dis = DIS + 1; now. U = V; Fa [v] = u; vis [v] = 1; que. push (now) ;}} int smaxi, smaxtag; int emaxi, emaxtag; void findcenter (int s, Int & Ma, Int & tag) {MA = 0, tag = s; BFS (s); int NS = maxtag; BFS (NS); int Ne = maxtag; int CNT = (Maxi + 1)/2; int NC = 0; int I = ne; while (1) {NC ++; If (NC> CNT) {tag = I; break;} I = Fa [I];} BFS (TAG); MA = Maxi;} int main () {int t, n, I, U, V; scanf ("% d", & T ); while (t --) {u = V =-1; scanf ("% d", & N); for (I = 0; I <= N; I ++) G [I]. clear (); for (I = 1; I <n; I ++) {scanf ("% d", & U, & V); G [u]. push_back (V); G [v]. push_back (U);} BFS (1); int S = maxtag; BFS (s); int e = maxtag; int CNT = (Maxi + 1)/2; int NC = 0; I = E; while (1) {NC ++; If (NC> = CNT) {u = I, V = Fa [I]; break ;} I = Fa [I];} findcenter (S, smaxi, smaxtag); findcenter (E, emaxi, emaxtag); printf ("% d \ n ", max (smaxi, emaxi), smaxtag, emaxtag) ;}return 0 ;}
View code
Zoj 3820 building fire stations calculate the midpoint + tree diameter + BFS