Question Description Please login Blue Bridge Cup official website to see it. It's not posted here.
At first I was using the adjacency matrix storage graph. The last data n is 10000, resulting in excessive memory and running errors. Using adjacency tables to store diagrams solves such problems. (But we don't know if the memory is over the game, what to do with it).
If you do a deep first search of the tree from each node, the timeout will run.
Looking at someone else's code hints, I produced a train of thought. It is possible to traverse the tree 2 times in depth.
The first traversal finds a terminal node that is contained in the longest road, and a deep-first search of the tree from that terminal node can find the longest way.
The code is as follows:
#include <iostream>#include<cstring>#include<vector>using namespacestd;#defineMAX (A, B) (a>b)? a:bConst intmax_n=10016;intV;typedef pair<int,int>P;vector<P>G[max_n];intVis[max_n];intans=-1;intPos;voidDfsintVintsum) { if(sum>ans) {ans=sum; POS=v; } Vis[v]=1; for(intI=0; I<g[v].size (); i++) {P pi=G[v][i]; intu=Pi.first; if(!Vis[u]) {DFS (U,sum+Pi.second); } }}intMain () {intN; CIN>>N; V=N; for(intI=0; i<n-1; i++) { intU,v,cost; CIN>>u>>v>>Cost ; G[u].push_back (P (v,cost)); G[v].push_back (P (u,cost)); } ans=-1; DFS (1,0); memset (Vis,0,sizeof(VIS)); Ans=-1; DFS (POS,0); cout<< ( One+Ten+ans) *ans/2<<Endl; return 0;}
Travel of Blue Bridge Cup ministers