From http://www.cnblogs.com/mjc467621163/archive/2011/07/11/2102834.html
# Include <iostream> # include <cstdio> # include <vector> # include <algorithm> using namespace STD; int n, m, Q, Y, K; struct node {int ID, Sala, height; int boss, child; // sub stores the position of the first-level subordinates. Child records the number of all subordinate vectors <int> sub; bool operator <(const node & O) const // in descending order {return Sala> O. sala; // No two employees have the same salary .}} person [30010]; int main () {int I, j; scanf ("% d", & N); While (n --) {scanf ("% d", & M, & Q); for (I = 0; I <m; ++ I) {scanf ("% d", & person [I]. ID, & person [I]. sala, & person [I]. height); person [I]. sub. clear (); person [I]. child = 0;} Sort (person, person + M); // employees are sorted in descending order of salary (I = s-1; I> = 0; -- I) {for (j = I-1; j> = 0; -- j) // immediate boss makes the least money than you do and the height cannot be lower than you if (person [J]. height> = person [I]. height) break; If (j> = 0) {person [I]. boss = J; person [J]. sub. push_back (I); // I is the first subordinate of J} else person [I]. boss =-1; // boss =-1 indicates no superiors} for (I = s-1; I> = 0; -- I) {If (person [I]. sub. size ()> 0) {for (j = 0; j <person [I]. sub. size (); ++ J) person [I]. child + = person [person [I]. sub [J]. child + 1; // you can know the total number of subordinates} int ID as long as you calculate all the subordinates at the first layer; while (Q --) {scanf ("% d ", & ID); for (I = 0; I <m; ++ I) if (person [I]. id = ID) break; If (person [I]. boss =-1) printf ("0% d \ n", person [I]. child); else printf ("% d \ n", person [person [I]. boss]. ID, person [I]. child) ;}} return 0 ;}