首页 > 试题广场 >

游历魔法王国

[编程题]游历魔法王国
  • 热度指数:108 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
魔法王国一共有n个城市,编号为0~n-1号,n个城市之间的道路连接起来恰好构成一棵树。
小易现在在0号城市,每次行动小易会从当前所在的城市走到与其相邻的一个城市,小易最多能行动L次。
如果小易到达过某个城市就视为小易游历过这个城市了,小易现在要制定好的旅游计划使他能游历最多的城市,请你帮他计算一下他最多能游历过多少个城市(注意0号城市已经游历了,游历过的城市不重复计算)。

输入描述:
输入包括两行,第一行包括两个正整数n(2 ≤ n ≤ 50)和L(1 ≤ L ≤ 100),表示城市个数和小易能行动的次数。
第二行包括n-1个整数parent[i](0 ≤ parent[i] ≤ i), 对于每个合法的i(0 ≤ i ≤ n - 2),在(i+1)号城市和parent[i]间有一条道路连接。


输出描述:
输出一个整数,表示小易最多能游历的城市数量。
示例1

输入

5 2
0 1 2 3

输出

3
N, L = map(int, input().split())

parents = [int(i) for i in input().split()]

nodes_depth = [0] * N

for i in range(N-2):
    nodes_depth[i+1] = nodes_depth[parents[i]] + 1

max_depth = max(nodes_depth)

if L <= max_depth:
    max_cities = L + 1
else:
    max_cities = max_depth + ((L - max_depth) // 2) + 1

if max_cities <= N:
    print(max_cities)
else:
    print(N)
--------------------- 
作者:ChrisMinions 
来源:CSDN 
原文:https://blog.csdn.net/qq_34617032/article/details/78573539 
版权声明:本文为博主原创文章,转载请附上博文链接!

发表于 2019-06-24 10:52:20 回复(0)
初学编程,哈哈,代码比较糙,大家看看就好。

#include <iostream>
#include <math.h>
using namespace std;

int main(){
    uint cityNum = 0;//题目中的n
    uint maxStep = 0;//题目中的l
    cin>>cityNum;
    cin>>maxStep;
    
    uint parent[10000];
    
    for(int i = 0 ; i < cityNum-1;i++){
        cin>>parent[i];
    }
    uint depth[10000];//用来保存节点深度的数组
    
    for(int j = 0 ; j < cityNum-1;j++){//获取深度为1的节点
        if(parent[j] == 0){
            depth[j] = 1;
        }
    }
    //更新每一座城市所在的节点深度(本题只需要最大节点深度,此处有些多余,循坏比较多,仅供参考)
    for(int k = 1;k<cityNum-1;k++){
        for(int j = 0 ; j < cityNum-1;j++){//获取深度为k的节点
                if(depth[j] == k){
                    for(int i = 0 ; i < cityNum-1;i++){
                        if(parent[i] == j+1){
                            depth[i] = k+1;
                    }
                }
            }
        }
    }
    
    //获取节点深度的最大值
    uint maxDepth = depth[0];//初始化赋值
    for(int i = 0 ; i < cityNum-1;i++){
        if(maxDepth<depth[i]){
            maxDepth = depth[i];
        }
    }
    
    if(maxDepth>=maxStep+1){
        cout<<maxStep+1;
    }else{//考虑回路
        if(cityNum<maxDepth+floor((maxStep-maxDepth)/2)+1){
            cout<<cityNum;//可以游历的城市数量比现有城市数量都大,比较难发生
        }else{
            cout<<(maxDepth+floor((maxStep-maxDepth)/2)+1);
        }
    }
}
编辑于 2022-05-14 22:03:03 回复(0)