修改天平 UVA 12166

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
[[3,7],6]
40
[[2,3],[4,5]]
Sample Output
1
0
3

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<map>
#include<algorithm>
#include<functional>
#define MAXN 1000
using namespace std;
char s[1123456];
map<long long ,int >mp;
void dfs(int l, int r, int dep)
{
    if (s[l] == '[')
    {
        int p = 0;
        for (int i = l + 1; i <= r - 1; i++)
        {
            if (s[i] == '[')
                p++;
            if (s[i] == ']')
                p--;
            if (p == 0 && s[i] == ',')
            {
                dfs(l+1, i-1, dep+1);
                dfs(i+1, r-1, dep+1);
            }
        }
    }
    else
    {
        int w;
        s[r+1] = '\0';
        sscanf(s+l, "%d", &w);
        mp[(long long)w<<dep]++;
    }
}
int main(){
	int T;
	cin>>T;
	while(T--){

		scanf("%s",s);
		mp.clear();
		dfs(0,strlen(s)-1,0);
		int sum=0,mx=0;
		for(map<long long, int>::iterator it=mp.begin();it!=mp.end();it++)
			sum+=it->second,mx=max(mx,it->second);
			printf("%d\n",sum-mx);
		
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值