UVA12166 修改天平

来源:互联网 发布:淘宝上那个吉他店最好 编辑:程序博客网 时间:2024/05/24 05:27
修改天平
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;}

0 0
原创粉丝点击