Recent ancestor of HDU 2586 LCA

Source: Internet
Author: User
/* The nearest common ancestor of the adjacent table + LCA mainly adopts the DFS (post-traversal order) + query set (no compression path is required) method to implement the back-order backtracking process, update the Father's Day node */# include <iostream> # include <cstdio> # include <algorithm> # include <cmath> # include <vector> using namespace STD; # define Manx 40009 vector <int> V [Manx], W [Manx], que [Manx], ans_num [Manx]; bool vist [Manx]; int n, m, father [Manx], DIS [Manx], ANS [203]; void Init () {for (INT I = 0; I <= N; I ++) {v [I]. clear (); W [I]. clear (); que [I]. clear (); ans_num [I]. clear (); Vist [I] = 0; father [I] = I; DIS [I] = 0 ;}} int find (INT X) {return x = Father [x]? X: Father [x] = find (father [x]);} void Union (int x, int y) {FATHER [find (y)] = find (x );} void Tarjan (INT now, int Val) {vist [now] = true; DIS [now] = val; For (INT Len = V [now]. size (), I = 0; I <Len; I ++) {int temp = V [now] [I]; If (vist [temp]) continue; tarjan (temp, Val + W [now] [I]); Union (now, temp);} For (INT Len = que [now]. size (), I = 0; I <Len; I ++) {int temp = que [now] [I]; If (! Vist [temp]) continue; ans [ans_num [now] [I] = dis [now] + dis [temp]-2 * Dis [find (temp)];} int main () {int t, q; scanf ("% d", & T); While (t --) {scanf ("% d", & N, & Q); Init (); int A, B, C; For (INT I = 1; I <n; I ++) {scanf ("% d", & A, & B, & C); V [A]. push_back (B); V [B]. push_back (a); W [A]. push_back (c); W [B]. push_back (c) ;}for (INT I = 0; I <q; I ++) {scanf ("% d", & A, & B ); que [A]. push_back (B); que [B]. push_back (a); ans_num [A]. push_back (I); ans_num [B]. push_back (I);} Tarjan (1, 0); For (INT I = 0; I <q; I ++) printf ("% d \ n ", ans [I]) ;}}


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: 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.