Travel of Blue Bridge Cup ministers

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.