public static void main(String[] args) {
Solution solution = new Solution();
// Initialize the rules with the sample input
List<List> rules
rules.add(new AbstractMap.SimpleEntry<>("parent1", Arrays.asList("child1", "child2")));
rules.add(new AbstractMap.SimpleEntry<>("parent2", Arrays.asList("child3", "child4")));
rules.add(new AbstractMap.SimpleEntry<>("parent3", Arrays.asList("parent1", "parent2")));
rules.add(new AbstractMap.SimpleEntry<>("parent4", Arrays.asList("child5", "child6")));
System.out.println(solution.startBuild("parent1")); // Output: [child1, child2]
System.out.println(solution.onComplete("child1")); // Output: []
System.out.println(solution.onComplete("child2")); // Output: [parent1]
System.out.println(solution.startBuild("parent3")); // Output: [child1, child2, child3, child4]
System.out.println(solution.startBuild("parent4")); // Output: [child5, child6]
}
}
class Solution {
List<Map.Entry<String, List>> rules = new ArrayList<>();
private Map<String, Integer> dependencyCount = new HashMap<>();
private Map<String, List> dependents = new HashMap<>();
private Map<String, List> fileDependencies = new HashMap<>();
private Set completedFiles = new HashSet<>();
private void initializeDependencies() {
for (Map.Entry<String, List<String>> entry : rules) {
String parent = entry.getKey();
List<String> children = entry.getValue();
fileDependencies.put(parent, children);
dependencyCount.put(parent, children.size());
for (String child : children) {
dependents.computeIfAbsent(child, k -> new ArrayList<>()).add(parent);
dependencyCount.putIfAbsent(child, 0);
}
}
}
// Give a list of files that can be completed directly from the target
public List<String> startBuild(String target) {
if (fileDependencies.isEmpty()) {
initializeDependencies();
}
Set<String> readyToBuild = new HashSet<>();
Queue<String> queue = new LinkedList<>();
Set<String> visited = new HashSet<>();
// Start with the target itself
queue.offer(target);
visited.add(target);
while (!queue.isEmpty()) {
String current = queue.poll();
// Check if any child of the current can be built
if (fileDependencies.containsKey(current)) {
for (String child : fileDependencies.get(current)) {
if (dependencyCount.get(child) == 0 && !completedFiles.contains(child)) {
readyToBuild.add(child);
}
if (!visited.contains(child)) {
queue.offer(child);
visited.add(child);
}
}
}
}
return new ArrayList<>(readyToBuild);
}
// If this target is completed, is there some next file that can be completed
public List<String> onComplete(String target) {
if (dependents.isEmpty()) {
initializeDependencies();
}
completedFiles.add(target);
List<String> nextToBuild = new ArrayList<>();
if (dependents.containsKey(target)) {
for (String dependent : dependents.get(target)) {
dependencyCount.put(dependent, dependencyCount.get(dependent) - 1);
if (dependencyCount.get(dependent) == 0 && !completedFiles.contains(dependent)) {
nextToBuild.add(dependent);
}
}
}
return nextToBuild;
}
