Test Instructions:
Given N -times input, each time a row a,b, indicating b is a father. Finally , the relationship between node 1 and node 2 "is the comparison depth".
N <=1000 , 1<=a,b<=2000
Analysis:
Test instructions very clear, I use a value for each nodeRanksaves the node's depth, so each time the nodeamerging the tree of the root node into a nodebas the root node of the tree above, I'm going to put the slave nodeaand NodeaThe following nodes are allRankvalues are added to the nodebof theRankvalues. In this way, a struct holds the information for each node, each time it merges two trees.DFSupdating these nodes isOKup.
Code implementation:
#include <cmath> #include <cstdio> #include <string> #include <cstring> #include <iostream > #include <algorithm>using namespace std; #define FIN freopen ("Input.txt", "R", stdin) struct node{in T Rank; Vector<int> Son; nodes[2000 + 5];void dfs (int pos, const int& val) {Nodes[pos]. Rank + = val; int num = Nodes[pos]. Son.size (); if (num = = 0) return; for (int i = 0; i < num; i++) {int &np = Nodes[pos]. Son[i]; DFS (NP, Val); }}void Init () {for (int i = 1; i <=; i++) {nodes[i]. Rank = 1; Nodes[i]. Son.clear (); }}int Main () {//FIN; int n, a, B; while (~SCANF ("%d", &n)) {init (); for (int i = 1; I <= n; i++) {scanf ("%d%d", &a, &b); NODES[B]. Son.push_back (a); DFS (A, nodes[b]. Rank); } if (Nodes[1]. Rank = = Nodes[2]. Rank) printf ("You Are my brother\n"); else if (nodes[1]. Rank > Nodes[2]. Rank) printf ("You Are my elder\n"); else printf ("You Are my younger\n"); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
2010 Liaoning Province Nbut 1218 "DFS implementation tree traversal and update"