Test instructions: Ask for the minimum number of leaf node weights that need to be changed for balance balancing.
Analysis: Balance will always have a weight, this weight can be determined by the weight and depth of a leaf node directly.
Here's an example:
Assuming that the root node depth is 0, the node 6 depth is 1, if the node is the benchmark (the node value is not changed), the balance should be balanced, the total weight is (6 << 1), and if the node 3 as the benchmark, the balance to balance, the total weight is also (3 << 2).
Thus, it is only required to calculate the total weight of each node as the basis, if the weight of the corresponding leaf node is the largest, then the balance under this weight change the number of leaf knot points at least.
#pragmaComment (linker, "/stack:102400000, 102400000")#include<cstdio>#include<cstring>#include<cstdlib>#include<cctype>#include<cmath>#include<iostream>#include<sstream>#include<iterator>#include<algorithm>#include<string>#include<vector>#include<Set>#include<map>#include<stack>#include<deque>#include<queue>#include<list>#defineMin (A, B) ((a < b) a:b)#defineMax (A, B) ((a < b)? b:a)typedefLong Longll;typedef unsignedLong LongLlu;Const intInt_inf =0x3f3f3f3f;Const intInt_m_inf =0x7f7f7f7f;Constll ll_inf =0x3f3f3f3f3f3f3f3f;Constll ll_m_inf =0x7f7f7f7f7f7f7f7f;Const intDr[] = {0,0, -1,1, -1, -1,1,1};Const intDc[] = {-1,1,0,0, -1,1, -1,1};Const intMOD = 1e9 +7;Const DoublePI = ACOs (-1.0);Const DoubleEPS = 1e-8;Const intMAXN =1000000+Ten;Const intMaxt =10000+Ten;using namespacestd;CharS[maxn];map<ll,int>MP;intCnt//Total leaf nodesvoidDfsintStintEtintDeep ) { if(S[st] = ='['){ intTMP =0; for(inti = st +1; I <= et; ++i) { if(S[i] = ='[') ++tmp; if(S[i] = =']') --tmp; if(!tmp && s[i] = =',') {DFS (St+1I1, Deep +1); DFS (i+1, et-1, Deep +1); } } } Else{ ++CNT; ll Sum=0; for(inti = st; I <= et; ++i) {Sum= Sum *Ten+ S[i]-'0'; } ++mp[sum <<Deep ]; }}intMain () {intT; scanf ("%d", &T); while(t--) {mp.clear (); CNT=0; scanf ("%s", s); intLen =strlen (s); DFS (0, Len-1,0); intAns =0; for(map<Long Long,int>::iterator it = Mp.begin (); It! = Mp.end (); ++it) {ans= Max (ans, (*it). second); } printf ("%d\n", CNT-ans); } return 0;}
UVA-12166 equilibrium Mobile (Modify balance) (Dfs string representation of the two-fork tree)