UVA - 12166 Equilibrium Mobile

来源:互联网 发布:气象数据下载 编辑:程序博客网 时间:2024/04/29 23:40

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

103

分析:

1.题目描述:点击打开链接

2.解题思路:本题利用dfs解决,不过思维上要发挥一些创造性。本题问至少要修改的砝码个数,那么首先可以想到要选一个基准砝码,其他所有的砝码都试图根据这个基准法吗而改变。不过本题的巧妙之处就在这里,只要以深度为depth(depth从0开始)重量为w的砝码为基准,那么就能求出整个天平的总重量,即w*2^(depth),在代码中可以简洁地表示为w<<depth。这样,我们只用统计每个可能的总重量对应了多少不需要改动的砝码,设一共有sum个砝码,总重量为sumw的天平对应的砝码个数是base[sumw],那么最终答案就是sum-max{base[i]}(i为所有可能的天平总重量)。本题在统计之前需要用dfs后序遍历该表达式

本题的解法有点类似于找每个元素的某个贡献值的大小(在本题中贡献值就是以它为基准算出的天平总重量),同时统计该贡献值下元素有几个,那么最后取最优值即可。这种思维也是竞赛中的常见思维,应予以重视。


#include <bits/stdc++.h>using namespace std;int cur;string s;map<long long, int> cnt;void dfs(int dep) {if(isdigit(s[cur])) {long long a = 0;while(isdigit(s[cur]))a = a*10 + s[cur++] - '0';cnt[a<<dep]++;}else{        cur++; dfs(dep+1);        cur++; dfs(dep+1);        cur++;}}int main(){ios::sync_with_stdio(false);int T; cin >> T; cin.get();while(T--) {cur = 0; cin >> s; cnt.clear(); dfs(0);int sum = 0, mx = 0;for(map<long long,int>::iterator it=cnt.begin(); it!=cnt.end(); it++)sum += it->second, mx = max(mx, it->second);cout << sum - mx << endl;}    return 0;}


1 0
原创粉丝点击