Brush question is encountered a problem: http://www.nowcoder.com/questionTerminal/b1303e827e7f4df4a816598d008bbe72
This problem to use and check the set to solve (Union-find), the Netizen summed up very detailed: http://blog.csdn.net/dm_vincent/article/details/7655764
and the collection mainly consists of two parts, find and union function. Where the Find function is to find the root node, theunion function merges the nodes. The Find and union functions are spelled differently depending on the initialization value
also slightly different.
Here is a netizen wrote the answer, slightly flawed, I modified the next, plus point notes:
intFind (vector<int>& ID,inti) { //only the root node or the disconnected point is negative, and the other point is the index value of its root node.//if it's not the root node, find the root node . while(Id[i] >=0) i =Id[i]; returni;}voidUnioned (vector<int>&id,intIintj) { //set the point at which the root value is small to the root node. if(Id[i] <Id[j]) {Id[i]+=Id[j]; ID[J]= i;//directly save the index of the root node. } Else{Id[j]+=Id[i]; Id[i]=J; }}intMain () {stringstr; intCount//number of input connected sets while(Cin >>str) { intLen =str.length (); //all initialized to -1.vector<int> ID (len,-1); CIN>>count; for(inti =0; I < count; i++) { intp, q; CIN>> P >>Q; intProot =find (ID, p); intQroot =Find (ID, q); if(Proot! =qroot) unioned (ID, proot, qroot);//Note: The root node is connected.} vector<vector<int>>Mat (len); for(inti =0; I < id.size (); i++) { if(Id[i] = =-1)Continue; intRoot =Find (ID, i); Mat[root].push_back (i);//position index (by root node) where each connected set is saved } // for(inti =0; I < mat.size (); i++) {vector<Char> CHS;//saving characters on a connected set//if it is not a root node, skip directly for(intj =0; J < Mat[i].size (); J + +) {chs.push_back (str[mat[i][j]); } sort (Chs.begin (), Chs.end ());//sort characters on the same connected set//write back in string for(intj =0; J < Mat[i].size (); J + +) Str[mat[i][j]]=Chs[j]; } cout<<str; }}
View Code
and check Set