Topic 2: Racing time limit:20000msSingle Point time limit:1000msMemory Limit:256MBDescribe
Gensokyo has a racetrack. There are n locations in the racetrack. There is also a one-way road between locations.
These roads make the racetrack a structure of an outward tree. In other words, the road connects the n sites into a tree with a root. And all the edges are from the father pointing to the child.
Because the fragrance likes to stimulate, every time she goes to the circuit will go from the root node, choose the longest path to play.
But now the scent feels the longest path is too short, and she intends to create a new road in the racetrack that will make the longest path the longest.
At the same time, if the road formed a ring, then there may be traffic accidents, so the fragrance of new roads can not lead to the emergence of the ring.
Can you help to figure out the longest path after a new road? Delicate fragrance know that the root node must be number 1th point.
Input
A number N of a row, representing the number of places.
Next N-1 line, two numbers a and b per line, indicates a one-way path from point A to to B. All points are labeled from 1 to N.
Data range:
n<=100000.
Output
A row represents the longest path after a new edge is created.
-
Sample input
51 22 31) 44 5
Sample output
4
Solution: If the tree is a chain, adding an edge does not increase the length of the longest path, otherwise the answer is the longest path + the longest path with no common edge path +1
#include <cstdio>#include<cstring>#include<string>#include<map>#include<vector>using namespaceStd;vector<int> e[100010];intdeep[100010];intML;intN;intSub_path;intDfsintv) {Deep[v]=0; for(intI=0; I<e[v].size (); i++){ intt =DFS (E[v][i]); if(t+1>DEEP[V]) Deep[v] = t+1; } returndeep[v];}voidFindans (intVintd) { for(intI=0; I<e[v].size (); i++){ intU =E[v][i]; if(deep[u]+d==deep[1]){ intTM =0; for(intj =0;j< E[v].size (); j + +){ if(I==J)Continue; if(DEEP[E[V][J]]>TM) TM =Deep[e[v][j]]; } if(SUB_PATH<TM) Sub_path =TM; Findans (U,d+1); } }}intMain () {scanf ("%d",&N); intb; for(intI=1; i<n;i++) {scanf ("%d%d",&a,&b); E[a].push_back (b); } Sub_path=0; DFS (1); Findsub_path (1,1); Sub_path+ = sub_path!=0; printf ("%d\n", sub_path+deep[1]); return 0;}
Hihocoder Challenge 14, Title 2: Racing