public boolean addVertex(Vertex<T> v) { boolean added = false; if (!verticesHash.containsKey(v.getName())) { added = vertices.add(v); verticesHash.put(v.getName(), v); } return added; }
public boolean removeEdge(Vertex<T> from, Vertex<T> to) { Edge<T> e = from.findEdge(to); if (e == null) return false; else { from.remove(e); return true; } }
public boolean addEdge(Vertex<T> from, Vertex<T> to, int cost) throws IllegalArgumentException { if (!verticesHash.containsKey(from.getName())) throw new IllegalArgumentException("from is not in graph"); if (!verticesHash.containsKey(to.getName())) throw new IllegalArgumentException("to is not in graph"); Edge<T> e = new Edge<T>(from, to, cost); if (from.findEdge(to) != null) return false; else { from.addEdge(e); return true; } }
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); }
public void clearState() { for (Vertex<T> x : vertices) x.setMarkState(VISIT_COLOR_WHITE); }