POJ 1330 Nearest Common Ancestors (Tree)

Source: Internet
Author: User

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)

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.