Problem UVA12166-Equilibrium Mobile
Accept:529 Submit:4330
Time Limit: 3000 mSec
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 gure underneath. You are given such a conguration, 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 gure, equilibrium can be reached by changing the middle weight from 7 to 3, so only 1 weight needs to changed.
Input
On the rst 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 dened 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,7],6]
40
[[2,3],[4,5]]
Sample Ouput
1
0
3
题解:这个题还是比较需要思维的,一开始考虑DP,想状态想得云里雾里,看了题解才发现做法如此机智。
对于一个已经平衡得天平,可以把砝码拆开,构造出来一个满二叉树,思路就是从这里来的,由于要求修改最少的砝码,所以必定会以一个砝码作为参照,或者说该砝码质量不变,这样以来,根据刚才的思路,整个天平的质量就出来了,对于每一个砝码都进行这样的操作,求出来n个总质量,取其中的众数,再用n减去该数就得到了最少要修改几个。
这个题读入的技巧很有必要学习一下。对于这种只在叶子节点有权值的二叉树来说,这个建树方式非常便捷。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <map>
using namespace std;
typedef long long LL; int cnt,sum;
char exp[];
map<LL,int> ID; void dfs(int l,int r,int depth){
if(exp[l] == '['){
int p = ;
for(int i = l+;i <= r;i++){
if(exp[i] == '[') p++;
else if(exp[i] == ']') p--;
if(p== && exp[i]==','){
dfs(l+,i-,depth+);
dfs(i+,r-,depth+);
}
}
}
else{
int weight;
sscanf(exp+l,"%d",&weight);
ID[(LL)weight*(<<depth)]++;
sum++;
}
} int main()
{
//freopen("input.txt","r",stdin);
int iCase;
scanf("%d",&iCase);
while(iCase--){
ID.clear();
cnt = ,sum = ;
scanf("%s",exp);
dfs(,strlen(exp)-,);
map<LL,int>::iterator iter;
int Max = ;
for(iter = ID.begin();iter != ID.end();iter++){
Max = Max > iter->second ? Max : iter->second;
}
printf("%d\n",sum-Max);
}
return ;
}