public static void BFS_Visit(Vertex<Integer> u) { Deque<Vertex<Integer>> q = new LinkedList<>(); q.add(u); while (!q.isEmpty()) { Vertex<Integer> v = q.poll(); v.setMarkState(Graph.VISIT_COLOR_GREY); for (Edge<Integer> x : v.getOutgoingEdges()) { Vertex<Integer> ver = x.getTo(); if (ver.getMarkState() == Graph.VISIT_COLOR_WHITE) { if (ver.getData() != 0) ver.setData(v.getData() + 1); ver.setParent(v); q.add(ver); } } v.setMarkState(Graph.VISIT_COLOR_BLACK); } }
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] input = in.readLine().split(" "); int n = Integer.parseInt(input[0]); int m = Integer.parseInt(input[1]); Graph<Integer> g = new Graph<>(); input = in.readLine().split(" "); int[] cats = new int[n + 1]; for (int i = 1; i <= n; i++) { cats[i] = Integer.parseInt(input[i - 1]); Vertex<Integer> v = new Vertex<>(Integer.toString(i), cats[i]); g.addVertex(v); } for (int i = 1; i < n; i++) { input = in.readLine().split(" "); int x = Integer.parseInt(input[0]); int y = Integer.parseInt(input[1]); Vertex<Integer> from = g.findVertexByName(Integer.toString(x)); Vertex<Integer> to = g.findVertexByName(Integer.toString(y)); g.insertBiEdge(from, to, 0); } BFS_Visit(g.findVertexByName("1")); int count = 0; for (int i = 1; i <= n; i++) { Vertex<Integer> vertex = g.findVertexByName(Integer.toString(i)); if (vertex.getOutgoingEdgeCount() == 1 && i != 1) { int maxi = 0; while (vertex.getParent() != null) { maxi = Math.max(maxi, vertex.getData()); // System.out.print(vertex.getName() + " "); vertex = vertex.getParent(); } // System.out.println(); maxi = Math.max(maxi, vertex.getData()); if (maxi <= m) count++; } } System.out.println(count); }