米哈游笔试

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,

// then press Enter. You can now see whitespace characters in your code.

class Node {

// 父亲编号

public int parval;

public boolean isleaf;

// 当前编号

public int val;

public Node(int parval, boolean isleaf, int val) {

this.isleaf = isleaf;

this.parval = parval;

this.val = val;

}

public Node() {

}

}

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int[] array = new int[2];

for (int i = 0; i < array.length; i++) {

array[i] = scanner.nextInt();

}

int count = array[0];

int k = array[1];

ArrayList<Node> nodes = new ArrayList<>();

for (int i = 0; i < count + 1; i++) {

nodes.add(new Node());

}

for (int i = 0; i < count - 1; i++) {

int[] nums = new int[2];

for (int j = 0; j < nums.length; j++) {

nums[j] = scanner.nextInt();

}

nodes.get(nums[0]).isleaf = false;

nodes.get(nums[0]).val = nums[0];

nodes.get(nums[1]).isleaf = true;

nodes.get(nums[1]).parval = nums[0];

nodes.get(nums[1]).val = nums[1];

}

int max = 0;

for (int i = 1; i <= count; i++) {

int step = calStep(nodes, nodes.get(i));

if (step <= k) {

max++;

}

if (nodes.get(i).isleaf && step < k) {

nodes.add(new Node(i, true, ++count));

}

}

System.out.println(max);

}

public static int calStep(ArrayList<Node> nodes, Node node) {

int cur = node.val;

int step = 0;

while (nodes.get(cur).parval != 0) {

cur = nodes.get(cur).parval;

step++;

}

return step;

}

}

我**没问题啊,给我0是为啥

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务