Give a graph to find out the arrangement of the minimum bandwidth. Specific requirements See Portal: UVa140
There are a few tricks that can simplify the writing of the Code.
The realization of the subject reference Rujia Teacher's source code, indeed gave me a lot of inspiration, thank teacher Liu.
Ideas:
- establish a double-shot relationship : The input string is traversed from character A to character Z, the characters appearing in the input are identified with the STRCHR function, and the identified characters are numbered, and the characters and corresponding numbers are stored in letter and ID respectively
- dimensionality Reduction : given in the input, is similar to the form of adjacency table two-dimensional form, if we use a two-dimensional data structure, will increase processing time for the output details of the processing difficulty, with 2 vectors to reduce the output to 1 dimensions, simplifying the calculation of bandwidth code, Actually, let's be more targeted.
- Store the necessary information-location : Array pos Each subscript represents the letter number, storing the corresponding position subscript, which is convenient for calculating the position.
- pruning : subtracting unnecessary calculations (although not necessary for the subject)
- use of library functions : The use of memcpy,strchr,strlen,next_permutation simplifies the code and highlights the logical part.
The code is implemented as follows:
1#include <cstdio>2#include <cstring>3#include <vector>4#include <algorithm>5 using namespacestd;6 7 Const intmaxn=Ten, inf=0x7fffffff;8 CharLETTER[MAXN], s[ -];//letter, input sequence9 intid[ the];//Number of lettersTen intP[MAXN];//A full array of traversed arrays, with the number of each letter stored One intPOS[MAXN];//record the position of each letter to avoid frequent use of STRCHR A - intMain () { - while(SCANF ("%s", &s), s[0]!='#'){ the intLen=strlen (s), n=0; - for(CharCh='A'; ch<='Z'; ch++)if(STRCHR (s,ch)! =NULL) { -letter[n]=ch; -id[ch]=n++; + } -vector<int>u,v; + for(intI=0; i<len;i++){ A intt=i;//Record start node ati+=2; - while(I<len && s[i]!=';'){ -U.push_back (Id[s[t]);//Join the Start node -V.push_back (Id[s[i]);//joins the neighboring nodes of the starting node -i++; - } in } - //Traversal + Pruning to intBandwidth=0, res=inf; + intBESTP[MAXN];//storing the final result - for(intI=0; i<n;i++) p[i]=i; the Do{ *Bandwidth=0;//initialize don't forget. $ for(intI=0; i<n;i++) pos[p[i]]=i;//position of the node where the record number is piPanax Notoginseng for(intI=0; I<u.size (); i++){ -Bandwidth=max (Bandwidth,abs (pos[u[i]]-pos[v[i])); the if(Bandwidth>=res) Break;//Pruning + } A if(bandwidth<Res) { thememcpy (Bestp,p,sizeof(p));//memcpy Faster +res=bandwidth; - } $} while(Next_permutation (p,p+n)); $ for(intI=0; i<n;i++) printf ("%c", Letter[bestp[i]]); -printf"%d\n", res); - } the}
UVa140 Bandwidth Small pruning + Double shot tips + Enumeration full array + small processing of strings