Although the official explanation is that the tree in this topic as a non-circular diagram, from the answer to the "1 as the root node" under the premise of this tree is set up, from the leaf node to access, pushed to the root node can--much like the dynamic planning of "bottom-up."
But the tree's construction is worrying: the given edge doesn't know which side is closer to the root node. So I gave the scheme simply at two vertices to add the other side of the child, wait until the time of the visit to deal with, according to the root node from 1 to start accessing this feature, add a "isvisited" to make a distinction.
Then use the stack to do non-recursive access to the tree
/** * for Best-coder problem 3 * * #include <iostream>using namespace std; #include <set> #include <stack>s Truct Node{public:node (): Misvisited (FALSE) {} bool misvisited; set< int > mchilds; set< int > mcolorset;}; int main () {int nnode, ncounting; while (Cin >> nnode >> ncounting) {Node node[50001]; int edge[50001][2]; for (int i=1; i<nnode; i++) {int A, B; Cin >> a >> b; Node[a].mchilds.insert (b); Node[b].mchilds.insert (a); } for (int i=0; i<ncounting; i++) {int n, color; CIN >> n >> color; Node[n].mcolorset.insert (color); } stack<int> Nodestack; Node[1].misvisited = true; Nodestack.push (1); do{int currenttop = Nodestack.top (); node& topnode = Node[currenttop]; Set<int> & Topchilds= Topnode.mchilds; Set<int> & topcolors = Topnode.mcolorset; for (Set<int>::iterator ci = topchilds.begin (); Ci! = topchilds.end (); ci++) {int child = *CI; if (node[child].misvisited) {topchilds.erase (child); Continue } node[child].misvisited = true; Nodestack.push (child); Break }//It ' s a leaf child if (topchilds.empty ()) {Nodestack.pop (); if (Nodestack.empty ()) continue; node& Topnode = node[nodestack.top ()]; TopNode.mColorSet.insert (Topcolors.begin (), Topcolors.end ()); TopNode.mChilds.erase (Currenttop); Continue }}while (!nodestack.empty ()); Output for (int i=1; i<=nnode; i++) {cout<< node[i].mcolorset.size (); if (i! = nnode) {cout << ""; }else{cout << Endl; } } }}
Best coder round#25 1003 tree non-recursive access