Title: Nearest Common Ancestors
Builds a tree based on the input and then asks the nearest common ancestor of 2 nodes.
Note the points:
(1) record the father of each node and use it at the comparative level;
(2) record level;
(3) record each node of the child,vector<int> V[m] written in the main function, placed outside the timeout .
Code:
#include <iostream>#include<vector>#include<cstdio>#include<cstdlib>#include<cstring>using namespacestd;Const intM =10001; //vector<int> v[m];intLevel[m];intFather[m];voidVisiteveryone (vector<int> v[],intOneint_level) {Level[one]=_level; for(vector<int>::iterator it = V[one].begin (); It! = V[one].end (); ++it) {Visiteveryone (V,*it, _level+1); }}intMain () {intt,n,a,b,i,j; scanf ("%d", &T); while(t--) {vector<int>V[m]; scanf ("%d", &N); memset (father,0, (n+1)*sizeof(int)); for(i =1; i < N; ++i) {scanf ("%d%d", &a, &b); FATHER[B]=A; V[a].push_back (b); } scanf ("%d%d", &a, &b); for(j=1; FATHER[J] >0&& J <= N; ++j); Visiteveryone (V, J,0); while(A! =b) {if(Level[a] <Level[b]) b=Father[b]; Elsea=Father[a]; } printf ("%d\n", a); } return 0;}
POJ 1330 Nearest Common Ancestors (Tree)