[数据结构] Equilibrium Mobile UVa12166

题目描述

给一棵深度不超过16的二叉树,代表一个天平。每个天平左右臂等长,树的子叶表示秤砣且其质量已知。求至少修改多少个秤砣的质量可以让整个天平平衡。

题解

如果这个二叉树满足题目中平衡的要求,那么树的每一层的值都相等,且第 D i 层的值与第 D i + 1 的关系为: D i = 2 D i + 1

这样可以这样解题。对每一个秤砣根据其所在的层数算出根的值。这样每一个秤砣都对应一个根节点的值,而一个根节点值棵对应多个秤砣。这样对应最多秤砣的情况就是最少修改的情况。最少修改次数就为秤砣总个数 n 减去某个根值对应最多的秤砣数 m .

AC代码

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

const int INF = 0x3f3f3f3f;

map<long long , int> mp;
int nodecnt = 0;

int CreateTree(){
    mp.clear();
    nodecnt = 0;
    int minch = 0;
    int knt = 0;
    char ch;
    scanf("%c", &ch);
    while(ch != '\n'){
        if(ch == '[') knt++;
        else if(ch == ']') knt--;
        else if(ch == ',') ;
        else{
            nodecnt++;
            long long num = 0;
            while('0'<=ch&&ch<='9'){
                num = (num*10)+(ch-'0');
                scanf("%c", &ch);
            }
            num = (num<<knt);
            if(!mp.count(num)) mp[num] = 0;
            mp[num]++;
            if(mp[num]>minch) minch = mp[num];
            continue;
        }
        if(scanf("%c", &ch) == EOF) break;
    }
    return minch;
}



int main(){
    freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    int n;
    cin>>n;
    getchar();
    while(n--){
        int a =  CreateTree();
        printf("%d\n", nodecnt - a);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/loyxCCS/article/details/80273782