TOJ 3009.Monkey Vines

平衡树猴子问题解析
本文介绍了一道关于平衡树的问题,猴子们如何通过合作保持树的平衡以获取食物。文章提供了一个C++实现的示例代码,展示了如何计算树的最大深度,并确保每个节点两侧的猴子数量相等。

题目链接 : http://acm.tju.edu.cn/toj/showp3009.html

Deep in the Amazon jungle, exceptionally tall trees grow that support a rich biosphere of figs and juniper bugs, which happen to be the culinary delight of brown monkeys.
Reaching the canopy of these trees requires the monkeys to perform careful navigation through the tall tree’s fragile vine system. These vines operate like a see-saw: an unbalancing of weight at any vine junction would snap the vine from the tree, and the monkeys would plummet to the ground below. The monkeys have figured out that if they work together to keep the vines properly balanced, they can all feast on the figs and juniper bugs in the canopy of the trees.

A vine junction supports exactly two sub-vines, each of which must contain the same number of monkeys, or else the vine will break, leaving a pile of dead monkeys on the jungle ground. For purposes of this problem, a vine junction is denoted by a pair of matching square brackets [ ], which may contain nested information about junctions further down its sub-vines. The nesting of vines will go no further than 25 levels deep.
······

这道题最大的难点在于要读懂题目:要让树保持平衡,需要多大。分析一下就知道关键是找到树的深度,题目不难。需要注意的是如果要读一行字符串用gets()函数,scanf()不能读空格、换行。

#include <stdio.h>
#include <iostream>
#include <math.h>
#include <cstring>
using namespace std;
int main(){
    int n,max,tmp;
    char vine[152];
    scanf("%d",&n);
    getchar();
    for(int cast=1;cast<=n;cast++){
        gets(vine);
        tmp=max=0;
        for(int i=0;i<strlen(vine);i++){
            if(vine[i]=='[') tmp++;
            else if(vine[i]==']') tmp--;
            if(tmp>max)
                max=tmp;
        }
        printf("%d %d\n",cast,int(pow(2.0,max)));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值