Title: Hire and Fire
The topic is translated into a data structure: achievements, add nodes, delete nodes, print nodes. Only the deletion of nodes is slightly more complex because the removal of the design-out tree adjustment.
The first thing to consider is how the tree is stored to make the problem easier.
1. We want to store each node's child, father and name. The child is stored because the first child may "upgrade", the storage father is to print, the name must also be printed;
2. We want to know each node of the subtree, delete node will involve adjustment;
3. We need to know the root node and store the CEO.
So our junction came out, as follows:
struct Tman { string name; *father; List<tman *> Sons;};
The ideas are in the comments.
The code is as follows:
#include <iostream>#include<map>#include<list>#include<string>using namespacestd;//Store Name, Father, child.structtman{stringname; Tman*father; List<tman *>sons;};//key is the node name, value is the subtree of the namemap<string, Tman *>Hash;//root node, point to CEO, print is to useTman *Root;voidPrintLongDEP, Tman *Now ) { if(now = NULL)return; for(Longi =1; I <= DEP; ++i) cout<<"+"; cout<<now->name<<Endl;; //Print each child's node recursively. for(List<tman *>::iterator j = Now->sons.begin (); J! = Now->sons.end (); + +j) Print (DEP+1, *j);}voidHires (stringN1,stringn2) {Tman*boss = Hash[n1];//father's child tree pointerTman *employee =NewTman ();//Create a new Tman structure to store the newly added nodes .Employee->name = n2;//the name of the newly added node.Employee->father = boss;//N1 is N2 's father.Boss->sons.push_back (employee);//put N2 in N1 's child listHASH[N2] = employee;//the newly added node also has a subtree .}voidFire (stringN1) {Tman*p = Hash[n1];//pointer to N1 nodeHash.erase (N1); while(P->sons.size () >0)//If the node you want to delete has children.{p->name = P->sons.front ()->name;//the first child replaced the father's positionHash[p->name] = p;//father's subtree to the first childp = P->sons.front ();//p moves down and always points to the first child queue} P->father->sons.remove (P);//The last node without a child "delete" is actually moved upDelete p;//Prevent Wild hands}voidsolve () {stringstr1,str2; Longi; CIN>>str1; Root=NewTman (); HASH[STR1]=Root; Root->name =str1; while(cin>>str1) { if(str1 = ="Print") {print (0, Root); cout<<"------------------------------------------------------------"<<Endl; } Else if(str1 = ="Kindle") {cin>>str2; Fire (STR2); } Else{cin>>str2; CIN>>str2; Hires (STR1, str2); } }}intMain () {solve (); return 0;}
POJ 2003 Hire and Fire (Tree)