UVA12166 修改天平

修改天平
Time Limit:3000MS     Memory Limit:0KB     64bit IO Format:%lld & %llu

题意:天平类似一个二叉树,要求修改最少的节点使天平平衡,可以利用搜索来一次遍历每个结点,如果以此节点重量 w 为准,那么整棵树的总重量就是 w << depth ;只要这个总和相等,即使w,depth不相等也是同一颗数,因为深度不同。


#include<stdio.h>
#include<string.h>
#include<map>
using namespace std;

char str[10000000];
int s;
map<long long int,int> m;
void dfs(int l,int r,int depth)
{
    if(str[l] == '[')
    {
        int x = 0;
        for(int i = l+1;i<r;i++)
        {
            if(str[i] == '[') x++;
            if(str[i] == ']') x--;
            if(x == 0 && str[i] == ',')
            {
                dfs(l+1,i-1,depth+1);//去掉左括号
                dfs(i+1,r-1,depth+1);//去掉右括号
                return;
            }
        }
    }
    else
    {
        long long int x = 0;
        for(int i = l;i<=r;i++)
            x = x*10+(str[i]-'0');
        s++;
        m[x << depth]++;
        return;
    }//w<<depth是以w为准,整个子树的总重量
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s",str);
        int l = strlen(str);
        s = 0;
        m.clear();
        dfs(0,l-1,0);
        map<long long int,int>::iterator it;
        int Mx = 0;
        for(it = m.begin();it!=m.end();it++)
            Mx = Mx>(*it).second ? Mx : (*it).second;
        printf("%d\n",s-Mx);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值