uva12166 修改天平 元素的贡献值-最优解

按元素的贡献值求最值的思想

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=24840
题解:
如果以每一个结点为基准计算总质量,并统计质量次数最多的那个,就是修改次数最少的,相当于每一个结点都贡献了以自己为基准的结果,因为总质量相同说明路径上又不需要更改的元素值。
思想:
例如:bfs求最短路,每一个结点提供的也是一种权值,也有贡献,最后通过计算贡献最少的即为最短路。
代码:

# include<iostream>
# include<cstdio>
# include<map>
# include<cstring>
# include<algorithm>
using namespace std;

int cnt;
string str;
map<long long,int>mp;

void solve(int l,int r,int d)
{
    if(str[l]=='['){
        int flag=0;
        for(int i=l+1;i<r;++i){
            if(str[i]=='[') ++flag;
            if(str[i]==']') --flag;
            if(!flag&&str[i]==','){
                solve(l+1,i-1,d+1);
                solve(i+1,r-1,d+1);
            }
        }
    }else{
        long long w=0;
        for(int i=l;i<=r;++i)
            w=w*10+str[i]-'0';
        ++cnt;
        ++mp[w<<d];
    }
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        mp.clear();
        cnt=0;
        cin>>str;
        solve(0,str.size()-1,0);
        int maxn=0;
        for(map<long long,int>::iterator it=mp.begin();it!=mp.end();++it)
            maxn=max(maxn,it->second);
        printf("%d\n",cnt-maxn);
    }
    return 0;
}

代码来源于网络

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值