Problem Description
A mobile is a type of kinetic sculpture constructed to take advantage of the principle of equilibrium. It consists of a number of rods, from which weighted objects or further rods hang. The objects hanging from the rods balance each other, so that the rods remain more or less horizontal. Each rod hangs from only one string, which gives it freedom to rotate about the string.
We consider mobiles where each rod is attached to its string exactly in the middle, as in the figure underneath. You are given such a configuration, but the weights on the ends are chosen incorrectly, so that the mobile is not in equilibrium. Since that's not aesthetically pleasing, you decide to change some of the weights.
What is the minimum number of weights that you must change in order to bring the mobile to equilibrium? You may substitute any weight by any (possibly non-integer) weight. For the mobile shown in the figure, equilibrium can be reached by changing the middle weight from 7 to 3, so only 1 weight needs to changed.
Input
On the first line one positive number: the number of testcases, at most 100. After that per testcase:
* One line with the structure of the mobile, which is a recursively defined expression of the form:
<expr> ::= <weight> | "[" <expr> "," <expr> "]"
with <weight> a positive integer smaller than 109 indicating a weight and [<expr>,<expr>] indicating a rod with the two expressions at the ends of the rod. The total number of rods in the chain from a weight to the top of the mobile will be at most 16.
Output
Per testcase:
* One line with the minimum number of weights that have to be changed.
Sample Input
3 [[3,7],6] 40 [[2,3],[4,5]]
Sample Output
这道题重点在于寻找基准数,例如
,以三为基准数,只需将7改成3。
基准数,即多少个可以不变的数,首先应该进行枚举,把每一个点都看作基准数,具体怎么改并不需要理会。
那么怎样才能知道最少应该该多少个呢?
把每一个点都看做基准数,可知最多要改多少个。
然后~
有一些不同的基准数,最后根据它们而改造成的平衡二叉树的总重量是相同的,所以当以这些基准数的其中一个作为基准来调整树时,其他的基准数是不需要变化的,也就是说这些造成
树的总重量相同的数都不需要改,那么不需要改的越多,需要改的就越少。
那么:
公式:由一颗平衡二叉树的某个节点求它的总重量:
设这个节点为w,深度为d,总重量为ww
ww=w*pow(2,d),即ww=w<<d
这道题完全是借鉴别人博客才明白的:http://blog.csdn.net/crazysillynerd/article/details/43876123
基本一样~~唉,没办法,自己太low了,不过好歹也敲了一遍,加深了理解。
#include"iostream" #include"cstdio" #include"cstring" #include"map" using namespace std; map<long long,int>book; int sum; string a; void biaoji(int depth,int b,int e) { if(a[b]=='[') { int p=0; for(int i=b+1;i<e;i++) { if(a[i]=='[') p++; if(a[i]==']') p--; if(p==0&&a[i]==',') { biaoji(depth+1,b+1,i-1); biaoji(depth+1,i+1,e-1); } } } else { long long w=0; for(int j=b;j<=e;j++) w=w*10+a[j]-'0'; sum++;